【问题标题】:React state stays the same in callback functionsReact 状态在回调函数中保持不变
【发布时间】: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


【解决方案1】:

状态更新函数可以用作这样的函数,具有任何额外的无副作用逻辑。

setHistoryState更新函数中移动条件:

const historyAdd = () => {
  setHistoryState((state) => {
    // here, state will always be up-to-date.
    if (state.currHistoryIdx < state.historyLength) {
      return {
        historyLength: state.currHistoryIdx + 1,
        currHistoryIdx: state.currHistoryIdx + 1,
      };
    }
    return {
      historyLength: state.historyLength + 1,
      currHistoryIdx: state.historyLength + 1,
    };
  });
};

我只能使用 state 参数在 setHistoryState 函数中获取实际状态,但这个解决方案不适合我,因为我有更复杂的函数。

无论用例或复杂性如何,在更新程序函数中使用最新状态都可能是解决此问题的方法。

也可以和useEffect结合使用,触发变更等

例如,here's a more complex situation which is solved with the same solution.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2020-12-15
    • 2020-04-11
    • 1970-01-01
    • 2020-04-11
    • 2017-11-12
    相关资源
    最近更新 更多