带有useReducer的useContext始终返回空状态,直到调度填充状态的操作为止

时间:2020-08-06 18:32:12

标签: reactjs use-context use-reducer

我想从在那里设置的状态数据中获取信息。

商店代码:

import React, { createContext, useContext, useReducer } from "react";
import { PatientEntry } from "../types";

import { Action } from "./reducer";

export type State = {
  patients: { [id: string]: PatientEntry },
  patient: undefined|PatientEntry
};

const initialState: State = {
  patients: {},
  patient:undefined
};

export const StateContext = createContext<[State, React.Dispatch<Action>]>([
  initialState,
  () => initialState
]);

type StateProviderProps = {
  reducer: React.Reducer<State, Action>;
  children: React.ReactElement;
};

export const StateProvider: React.FC<StateProviderProps> = ({
  reducer,
  children
}: StateProviderProps) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StateContext.Provider value={[state, dispatch]}>
      {children}
    </StateContext.Provider>
  );
};
export const useStateValue = () => useContext(StateContext);

设置和获取代码。

const [state, dispatch] = useStateValue();
React.useEffect(() => {
 const fetchPatient = async () => {
      try {
{
const { data: patientFromApi } = await axios.get<PatientEntry>(`${apiBaseUrl}/patients/${id}`);





console.log("before dispatch")
console.log(state)

        dispatch({ type: "SET_PATIENT", payload: patientFromApi });
        console.log(Object.keys(patientFromApi))

}

      } catch (e) {
        console.error(e);
      }
    };
    fetchPatient();


  }, [dispatch]);

无论何时导航到该页面,每次必须首先在此设置数据之前,状态始终是初始状态。怎么得到它?

即使上下文使用者也无济于事

0 个答案:

没有答案