简体   繁体   English

React挂钩:使用useEffect时无法获取状态更新

[英]React hooks: Not getting the state update when using useEffect

I'm having an issue when mixing useState and the useEffect hook. 混合useStateuseEffect挂钩时出现问题。 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 docsRFC:为什么它是异步的?

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.

相关问题 使用 React 钩子从另一个页面使用 useEffect 更新状态 - Update state with useEffect from another page using React hooks 在 React Hooks 中使用 useEffect 更新对象数组 - update array of objects using useEffect in React Hooks 如何使用 socket.io-client 在 useEffect 挂钩中更新 React state - How update React state in useEffect hooks with socket.io-client 反应挂钩中的另一个卸载useEffect不会影响状态更改 - Change of state is not getting affected in another unmount useEffect in react hooks State 在使用 setstate 与钩子反应时没有更新 - State is not gatting update when using setstate in react with hooks 使用反应挂钩更改导入的变量时更新 state - Update state when imported variable changes using react hooks 使用 React 更新二维数组并挂钩 useState 和 useEffect - Update 2d array using React and hooks useState and useEffect 使用钩子做出反应时没有得到更新的 state 值? - not getting updated state value in react using hooks? 使用 React Hooks,使用“useState”和“useEffect”,有没有办法渲染一个状态直到状态有一个值? - Using React Hooks, using "useState" and "useEffect", is there a way to render a state waiting till the state has a value? 反应钩子 useEffect 更新 window.innerHeight - react hooks useEffect update window.innerHeight
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM