我试图在回调中异步调用 setState,问题是当我的函数调用 setState 时,状态已被另一个发生的事件更新。有没有办法从嵌套回调中查询当前状态?
这是一个简单的演示,展示了我遇到的问题:
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'));