Javascript React钩子问题:为什么这段代码只渲染3次?
它渲染两次,随后的setActive True不会触发另一次渲染。有什么好处Javascript React钩子问题:为什么这段代码只渲染3次?,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,它渲染两次,随后的setActive True不会触发另一次渲染。有什么好处 因为您在useffect内部使用setState,这会导致额外的渲染 见: // why is this rendering 3 times and not 2 or 4? import React, { useState, useEffect } from "react"; import ReactDOM from "react-dom"; import "./s
因为您在
useffect
内部使用setState
,这会导致额外的渲染
见:
// why is this rendering 3 times and not 2 or 4?
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function useVariantActive(variant) {
const [isActive, setIsActive] = useState(false);
useEffect(() => {
setIsActive(true);
setTimeout(() => {
setIsActive(true);
}, 1000);
}, [variant]);
return isActive;
}
function ExampleComponent() {
const varians = ["variant1"];
const var1 = useVariantActive(varians);
console.log("render", var1);
return <div>wakka</div>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ExampleComponent />, rootElement);
if (isActive !=== true) {
setIsActive(true)
}