直接使用使用效果中包含的几个状态
考虑依赖性阵列中具有2个不同状态的使用效应。每当两种状态中的任何一个更新时,使用效果挂钩都会运行,但是如果我更新其中一个状态,我是否可以访问其他内部使用效果的最后值?如果没有,最好的方法是什么?
function Component() {
const [state1, setState1] = useState('');
const [state2, setState2] = useState('');
useEffect(() => {
console.log(state1, state2)
}, [state1, state2]);
return <>...</>
}
Considering an useEffect with 2 different states in the dependency array. The useEffect hook will run whenever any of those two states are updated, but if i update one of them, will i have access to the lastest value of the other inside useEffect? And if not, what is the best approach to it?
function Component() {
const [state1, setState1] = useState('');
const [state2, setState2] = useState('');
useEffect(() => {
console.log(state1, state2)
}, [state1, state2]);
return <>...</>
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
内部的回调将根据依赖项数组有条件地渲染后运行。如果您的状态值在相同的渲染周期中更新,则将它们进行批处理(通过React),并且下一个渲染周期将在
useFeffect
回调中显示正确的值。如果仅更新其中任何一个,则不必担心另一个值,因为
useffect
中的回调也将使用其他变量的最近更新值。注意:您唯一可能面临的问题是当您由于关闭而具有陈旧的状态值时,这是一种特定情况。
The callback inside
useEffect
will run after the render conditionally based on dependency array.If your state values are updated in the same render cycle then they are batched (by React) and the next render cycle will show both the correct values in the
useEffect
callback.If you only update any one of them, you do not have to worry about the other value because the callback in
useEffect
will be using the recently updated value of the other variable too.Note: The only time you might face an issue is when you have stale state values because of closure, but that is a specific case.