为什么这个 useEffect (第一个)不能在依赖项更改时运行?
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)->雷德纳-> dom更新->布瑟油漆->运行效果
对于重新渲染:除了惰性初始化器和运行新效果之前的效果清理之外的所有内容。
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>
);
}
I think this is the order of execution for first render:
run lazy intializers (or we can say run useState) -> redner -> dom update -> broser paint -> run effect
And for re-render: all the things except lazy intializers and effect cleanup before running new effects.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Eslint
像这样发出警告您需要将
useState
forcount
声明移动到将其用作依赖项的useEffect
之前。Eslint
warns like thisYou need to move
useState
forcount
declaration before theuseEffect
which uses it as a dependency.您的第一个效果是在定义之前使用
count
,因此它始终是undefined
。You're first effect is using
count
before it has been defined, so it is alwaysundefined
.