我想从在那里设置的状态数据中获取信息。
商店代码:
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]);
无论何时导航到该页面,每次必须首先在此设置数据之前,状态始终是初始状态。怎么得到它?
即使上下文使用者也无济于事