【发布时间】:2020-05-01 17:35:03
【问题描述】:
我在 React 状态管理方面遇到了问题。 我想在单击按钮后使用 Context API 更新全局状态,然后使用更新后的状态执行其他操作。
按钮将动作分派到全局状态。但是,当我尝试在之后立即读取状态时,更改不会反映,直到应用重新渲染。
const App = () => {
const playerRef = useRef();
const { state, addPlayers } = useContext(playerContext);
// subscribe playerRef changes to global state,
useEffect(() => {
playerRef.current = state;
console.log("players #", playerRef.current.length);
}, [state]);
const add = useCallback(() => {
// dispatch an add players action to the store
addPlayers([{ name: "new" }, { name: "newer" }]);
// PROBLEM: Need latest state value here after dispatch
// but it's not immediately reflected here
console.log("player # after dispatch ", playerRef.current.length);
// do something with the new state
}, [playerRef, addPlayers]);
const handleSubmit = () => {
add();
};
return (
<div>
<p>Players: {String(state.map(player => player.name))}</p>
<button type="button" onClick={handleSubmit}>
AddPlayers
</button>
</div>
);
};
export default App;
link 到代码框查看完整的应用程序。 谢谢。
【问题讨论】:
标签: reactjs state react-context