[英]React hooks stale state
I'm trying to call setState asynchronous in a callback, the issue is that by the time my function calls setState, the state was updated by another event that happened. 我试图在回调中调用setState异步,问题是当我的函数调用setState时,状态由另一个发生的事件更新。 Is there a way to query the current state from a nested callback?
有没有办法从嵌套回调查询当前状态?
Here's a simple demo that showcases what I'm running into: 这是一个简单的演示,展示了我遇到的内容:
import React, { Component, useState } from 'react';
import { render } from 'react-dom';
function App() {
const [state, setState] = useState({value: 0});
const click = async () => {
setTimeout(() => setState({value: state.value + 10}), 300);
async function apiCall(state) {
// fake it for now
return new Promise((res) => {
setTimeout(() => {
// !!!Get the latest state here!!!
res({value: state.value + 1});
}, 1000)
});
}
const newState = await apiCall(state);
setState(newState);
}
return (
<div>
Value: {state.value}
<button onClick={click}>Update</button>
</div>
);
}
render(<App />, document.getElementById('root'));
useState
has a function updater form. useState
具有函数更新程序形式。 You can use that to get the latest state value before updating. 您可以使用它在更新之前获取最新的状态值。
const [val ,setVal] = React.useState(initVal);
const obj = { str: 'Hello' };
// Merge state form —
seVal(obj);
// Function updater form —
seVal(prevState => {
// Object.assign would also work
return {...prevState, ...{ str: prevState.str + ' World' }};
});
So your example would become 所以你的榜样就会变成
setTimeout(() => setState(prevState => ({value: prevState.value + 10})), 300);
Ref to docs — hooks-reference.html#functional-updates 参考文档 - hooks-reference.html #functional-updates
I have also updated your codesandbox to get it to work with comments. 我还更新了您的codesandbox以使其与评论一起使用。 codesandbox
codesandbox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.