【发布时间】:2020-08-25 21:10:11
【问题描述】:
在我的代码中,我有一个提供程序组件。在这个组件中,我有状态对象和一些改变状态的函数。问题是我想根据状态值更改状态,但在我的函数中,状态与初始化时保持相同。
我的部分代码:
const AppContextProvider = () => {
const [historyState, setHistoryState] = useState({
historyLength: 0,
currHistoryIdx: 0,
});
const historyAdd = () => {
if (historyState.currHistoryIdx < historyState.historyLength)
setHistoryState((state) => ({
historyLength: state.currHistoryIdx + 1,
currHistoryIdx: state.currHistoryIdx + 1,
}));
else
setHistoryState((state) => ({
historyLength: state.historyLength + 1,
currHistoryIdx: state.historyLength + 1,
}));
};
return (
<AppContext.Provider
value={{ state, centerState, rpState, historyState, functions }}
>
<App />
</AppContext.Provider>
);
};
我需要检查状态以决定如何更改它,但在此函数中,状态始终与初始化时保持一致,因此,我的状态无法正常工作。
我只能使用state 参数在setHistoryState 函数中获取实际状态,但是这个解决方案不适合我,因为我有更复杂的函数。另外,如果您使用useEffect 来检查状态是否发生变化,它会在控制台中显示实际状态。
我做错了什么,我该如何解决?
【问题讨论】:
-
我不知道这是否可以解决您的问题,因为我从未在 Context 组件上设置状态,但尝试这样做: setHistoryState({historyLength: historyState.historyLength + 1, currHistoryIdx: historyState.currHistoryIdx + 1})。正如我所说,我不知道这是否可以帮助您解决问题,如果不能告诉我,我会尝试编写解决方案。
标签: javascript reactjs