[英]React hooks: Not getting the state update when using useEffect
I'm having an issue when mixing useState
and the useEffect
hook. 混合
useState
和useEffect
挂钩时出现问题。 I can't seem to reference the new query
state in onReady()
. 我似乎无法在
onReady()
引用新的query
状态。
function Foo() {
const [ query, setQuery ] = React.useState('initial query');
React.useEffect(() => {
myLibClient.onReady(onReady)
}, []);
function onReady() {
const newQuery = myLibClient.createQuery({ options });
setQuery(newQuery);
console.log(query); // initial query :(
}
return null;
}
Can anyone see what I'm doing wrong or explain why this doesn't work? 谁能看到我在做什么错或解释为什么这行不通?
The issue here is that like this.setState
in the class-based react components, the setQuery
function also sets the state asynchronously. 这里的问题是,像
this.setState
在反应基于类的元件, setQuery
功能也设置状态异步。
See Reference react docs and RFC: Why it is asynchronous? 请参阅参考react docs和RFC:为什么它是异步的?
So if you try to access the value just after setting the state, you'll get the older value. 因此,如果您尝试在设置状态后立即访问该值,则将获得较旧的值。
You can verify this behavior here. 您可以在此处验证此行为。 https://codesandbox.io/s/2w4mp4x3ry .
https://codesandbox.io/s/2w4mp4x3ry 。 (See the file named Counter.js) You'll see that before and after values for counter are same.
(请参阅名为Counter.js的文件)您将看到counter的前后值是相同的。
If you want to access the updated value, you can access it in the next render cycle. 如果要访问更新的值,则可以在下一个渲染周期中访问它。 I have created another example where you can see that new query value is being rendered.
我创建了另一个示例,您可以看到正在呈现新的查询值。
https://codesandbox.io/s/8l7mqkx8wl (See the file named Counter.js) https://codesandbox.io/s/8l7mqkx8wl (请参阅名为Counter.js的文件)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.