export default function App() {
// as the useState runs before useEffect,
// it means count is avaliable to use in the useEffect
// but why it is not running?
useEffect(() => {
console.log("I only run on first render.", count);
},[count]);
useEffect(() => {
console.log("I runs on every render/re-render", count);
});
// if i use const in place of var, it throws error of lexical scope
// but as useState run before the effect the count is already in scope, right?
var [count, setCount] = useState(0);
useEffect(() => {
console.log("run on first render and whenever the count changes", count);
}, [count]);
return (
<div className="App">
<p>Count: {count}</p>
<button onClick={() => setCount((prev) => prev + 1)}>count +</button>
</div>
);
}
我认为这是第一次渲染的执行顺序:
运行延迟初始化程序(或者我们可以说运行 useState) -> redner -> dom update -> browser Paint -> run Effect
对于重新渲染:除了惰性初始化器和运行新效果之前的效果清理之外的所有内容。
Eslint
像这样警告
var count:数字“count”在定义之前就已使用。
(定义前不使用)eslint
你需要移动useState
for count
之前的声明useEffect
它将它用作依赖项。
var [count, setCount] = useState(0);
useEffect(() => {
console.log("I only run on first render.", count);
}, [count]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)