反应挂钩陈旧状态 [英] React hooks stale state
问题描述
我试图在回调中异步调用 setState,问题是当我的函数调用 setState 时,状态已被另一个发生的事件更新.有没有办法从嵌套回调中查询当前状态?
这是一个简单的演示,展示了我遇到的问题:
https://stackblitz.com/edit/react-uybyyn
import React, { Component, useState } from 'react';从'react-dom'导入{渲染};功能应用(){const [state, setState] = useState({value: 0});const click = async() =>{setTimeout(() => setState({value: state.value + 10}), 300);异步函数 apiCall(state) {//暂时伪造它返回新的承诺((res)=> {setTimeout(() => {//!!!在此处获取最新状态!!!res({value: state.value + 1});}, 1000)});}const newState = 等待 apiCall(state);设置状态(新状态);}返回 (<div>值:{state.value}<button onClick={click}>更新</button>
);}render(
useState
有一个函数更新器形式.您可以使用它在更新之前获取最新的状态值.
const [val ,setVal] = React.useState(initVal);const obj = { str: '你好' };//合并状态表单 —seVal(对象);//函数更新器表单 —seVal(prevState => {//Object.assign 也可以返回 {...prevState, ...{ str: prevState.str + 'World' }};});
所以你的例子会变成
setTimeout(() => setState(prevState => ({value: prevState.value + 10})), 300);
参考文档 — hooks-reference.html#functional-updates一个>
我还更新了您的代码和框以使其能够处理评论.codesandbox
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.com/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'));
useState
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 become
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 comments. codesandbox
这篇关于反应挂钩陈旧状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!