【问题标题】:React useReducer don't update state in React contextReact useReducer 不会在 React 上下文中更新状态
【发布时间】:2021-03-02 15:39:13
【问题描述】:

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

context.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>;

可能是什么问题?

【问题讨论】:

    标签: javascript reactjs react-hooks react-context use-reducer


    【解决方案1】:

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

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

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

    你可以在你的 reducer 中 console.log(action.payload) 来查看 'test str' 何时进入 reducer 操作。

    【讨论】:

    • console.log(action.payload) 返回“test str”。在 setTimeout 之前执行的 return 语句。如果我设置 20000 持续时间 - 结果相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2019-07-18
    相关资源
    最近更新 更多