React Context 和 useReducer 未设置状态

时间:2021-03-17 17:47:03

标签: reactjs context-api use-reducer

我正在创建一个上下文,它将发出请求并将数据设置为供多个组件使用的全局存储,该上下文将首先检查存储中是否存在现有数据,如果它不存在,它将使然后请求使用 reducer 设置状态。

但是,在我当前的设置中,即使在调度操作来设置状态后,我的状态也始终为空。

这是我的背景:

const initialState = {
  vocabulary: {},
};

export const VocabularyContext = createContext({ state: initialState } as Context);

export const { Provider: VocabularyProvider, Consumer: VocabularyConsumer } = VocabularyContext;

export const VocabularyContainer = ({ children }) => {
  const [state, dispatch] = useReducer(VocabReducer, initialState);

  const handleGetVocabulary = async (namespace: string) => {
    if (state.vocabulary[namespace]) return state.vocabulary[namespace];
    const vocabulary = await VocabularyService.getVocabularyByNamespace(namespace);

    dispatch({ namespace, type: 'ADD_VOCAB', vocabulary });
    return vocabulary;
  };

  return (
    <VocabularyProvider value={{ dispatch, getVocabulary: handleGetVocabulary, state }}>{children}</VocabularyProvider>
  );
};

这是我的减速器:

const VocabReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_VOCAB':
      return {
        ...state,
        vocabulary: { ...state.vocabulary, [action.namespace]: action.vocabulary },
      };
    default:
      return state;
  }
};

我正在与提供程序的子组件中的上下文进行交互:

  const { getVocabulary } = useContext(VocabularyContext);
  useEffect(() => {
    const handleVocabulary = async () => {
      const vocabulary = await getVocabulary('namespace');

      setProgramVocabulary(vocabulary);
    };

    handleVocabulary();
  }, []);

我试过从子组件分派,但也不起作用,即使我已经检查过并且使用正确的数据正确分派了操作,我的减速器的状态总是返回为空。

0 个答案:

没有答案
相关问题