无法读取上下文提供者中的useReducer挂钩更新的状态

时间:2019-04-02 14:33:33

标签: javascript reactjs react-hooks react-context

我正在使用useReducer钩子来管理状态,但似乎在读取上下文提供程序中的更新状态时遇到问题。

我的上下文提供者负责获取一些远程数据并根据响应更新状态:

import React, { useEffect } from 'react';
import useAppState from './useAppState';


export const AppContext = React.createContext();

const AppContextProvider = props => {
  const [state, dispatch] = useAppState();

  const initialFunction = () => {
    fetch('/some_path')
      .then(res => {
        dispatch({ type: 'UPDATE_STATE', res });
      });
  };

  const otherFunction = () => {
    fetch('/other_path')
      .then(res => {
        // why is `state.stateUpdated` here still 'false'????
        dispatch({ type: 'DO_SOMETHING_ELSE', res });
      });
    }
  };

  const actions = { initialFunction, otherFunction };

  useEffect(() => {
    initialFunction();
    setInterval(otherFunction, 30000);
  }, []);

  return (
    <AppContext.Provider value={{ state, actions }}>
      {props.children}
    </AppContext.Provider>
  )
};

export default AppContextProvider;

useAppState.js非常简单,如下:

import { useReducer } from 'react';


const useAppState = () => {
  const reducer = (state, action) => {
    switch (action.type) {
      case 'UPDATE_STATE':
        return {
          ...state,
          stateUpdated: true,
        };
      case 'DO_SOMETHING_ELSE':
        return {
          ...state,
          // whatever else
        };
      default:
        throw new Error();
    }
  };


  const initialState = { stateUpdated: false };

  return useReducer(reducer, initialState);
};


export default useAppState;

问题如上所述,为什么上下文提供者的state.stateUpdated中的otherFunction仍然是false?我如何使用同一功能的最新更改访问状态? / p>

1 个答案:

答案 0 :(得分:1)

state永远不会改变该功能

state永远不会在该函数中更改的原因是state仅在重新渲染时更新。因此,如果要访问state,则有两个选择:

  1. useRef来查看state的将来值(您必须修改reducer才能使它工作)
const updatedState = useRef(initialState);
const reducer = (state, action) => {
  let result;
  // Do your switch but don't return, just modify result

  updatedState.current = result;
  return result;
};

return [...useReducer(reducer, initialState), updatedState];
  1. 您可以在每次状态更改后重置setInterval,以使其看到最新状态。但是,这意味着您的间隔可能会中断很多。
const otherFunction = useCallback(() => {
  fetch('/other_path')
    .then(res => {
      // why is `state.stateUpdated` here still 'false'????
      dispatch({ type: 'DO_SOMETHING_ELSE', res });
    });
  }
}, [state.stateUpdated]);

useEffect(() => {
  const id = setInterval(otherFunction, 30000);
  return () => clearInterval(id);
}, [otherFunction]);