首页 > 解决方案 > React useReducer 不会在 React 上下文中更新状态

问题描述

React useReducer 不会在 React 上下文中更新状态。但在返回部分状态数据正确呈现。这是示例:

上下文.js

const globalContext = React.createContext();
const initialState = {
  statuses: null,
};
const globalReducer = (state, action) => {
  switch (action.type) {
    case 'SET_STATUSES':
      return { ...state, statuses: action.payload };
    default:
      return state;
  }
};
export const GlobalState = ({ children }) => {
  const [state, dispatch] = React.useReducer(globalReducer, initialState);

  return <globalContext.Provider value={{ state, dispatch }}>{children}</globalContext.Provider>;
};

export const useGlobalState = () => {
  const context = React.useContext(globalContext);
  return context;
};

comeChild.js

const { state, dispatch } = useGlobalState();
const testFn = () => {
  console.log(state); // -> {statuses: null} :here is issue
};
React.useEffect(() => {
  console.log(state); // -> {statuses: null} :as expected
  dispatch({ type: 'SET_STATUSES', payload: 'test str' });
  console.log(state); // -> {statuses: null} :here is issue
  testFn();
  setTimeout(() => {
    console.log(state); // -> {statuses: null} :here is issue
  }, 3000);
}, []);

return <div>
  {state.statuses && <div>{state.statuses}</div>}// -> 'test str'
</div>;

可能是什么问题?

标签: javascriptreactjsreact-hooksreact-contextuse-reducer

解决方案


我对上下文和 useReducer 很陌生,但我的猜测是 React 中的良好状态“逻辑”。React 更新状态是异步的而不是同步的,这可能会导致这些行为。

您的 reducer 和 context 显然有效,因为它在您的 return 语句中输出正确的状态。这是因为你的state.statuses && 条件,说明你要返回 div WHEN state.statuses "exist" 可以这么说。

所以对我来说这看起来没什么问题,只是 React 是 React 与状态更新。

您可以console.log(action.payload)在减速器中查看“test str”何时进入减速器操作。


推荐阅读