状态在页面上保存得很好,并且可以更改和交互,但是一旦我导航到另一个页面 - 状态就会重置
整个商店和 createContext 是
type Action2 =
{
type: "ON";
payload: boolean;
}
| {
type: "OFF";
payload: boolean;
}
type State2 = {
isLoggedIn: boolean
};
const reducer2 = (state: State2, action: Action2): State2 => {
switch (action.type) {
case "ON":
return {
isLoggedIn:true
};
case "OFF":
return {
isLoggedIn:false
};
default:
return state;
}
};
const initialState: State2 = {
isLoggedIn: false
};
初始化状态
const [state2, dispatch2] = React.useReducer(reducer2, {"isLoggedIn":false});
用于更改状态的按钮
<Button onClick={()=>dispatch2({type:"ON",payload:true})}>
ON
</Button>
<Button onClick={()=>dispatch2({type:"OFF",payload:true})}>
OFF
</Button>
为路由中呈现的元素提供上下文
<Route exact path="/:id" >
<MyContext.Provider value={[state2, dispatch2]}>
<React.Fragment>
<PatientPage settingpatient={fetchPatient} context={context}/>
</React.Fragment>
</MyContext.Provider>
</Route>
在我从上下文访问状态的元素中
const theme2 = React.useContext(MyContext);
它总是 {isLoggedIn:false}