admin管理员组文章数量:1414614
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. 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'));
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. 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:
https://stackblitz./edit/react-uybyyn
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'));
Share
Improve this question
asked Jun 26, 2019 at 23:22
qwertymkqwertymk
35.4k30 gold badges124 silver badges184 bronze badges
0
1 Answer
Reset to default 7useState
has a function updater form. 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 bee
setTimeout(() => setState(prevState => ({value: prevState.value + 10})), 300);
Ref to docs — hooks-reference.html#functional-updates
I have also updated your codesandbox to get it to work with ments. codesandbox
本文标签: javascriptReact hooks stale stateStack Overflow
版权声明:本文标题:javascript - React hooks stale state - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745173980a2646144.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论