我试图学习文字。 我能做简单的使用,只看一页。 然而,当我想要利用情况确定国家时,我却不能让它适当地确定国家,这表现在它无法在网页上重新接手。
应用。
export interface User {
isSubscribed: boolean;
name: string;
}
const App: React.FC = () => {
const [user, setUser] = useState<User>({
isSubscribed: true,
name: You ,
})
return(
<IonApp>
<IonReactRouter>
<IonRouterOutlet>
<DashboardContext.Provider value={{user, setUser}}>
<Route exact path="/home">
<Home />
</Route>
<Route exact path="/">
<Redirect to="/home" />
</Route>
</DashboardContext.Provider>
</IonRouterOutlet>
</IonReactRouter>
</IonApp>
)
};
export default App;
内容:
export interface DashboardInterface {
user: User
setUser: Dispatch<SetStateAction<User>>
}
export const DashboardContext = createContext<DashboardInterface>(undefined);
export function useUserContext() {
const {user, setUser} = useContext(DashboardContext)
if (user===undefined){
throw new Error("useUserContext must be used with a Dashboard Context")
}
return {user, setUser}
}
住宅区
const Home: React.FC = () => {
interface Thing {
title: string;
nickname: string
}
const {user, setUser }= useUserContext()
const [thing, setThing]=useState<Thing>({
title: "Mr",
nickname: "Morale",
})
useEffect(() => {
console.log("in the useEffect")
},[user])
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>User {user.name} {thing.nickname}</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<IonHeader collapse="condense">
<IonToolbar>
<IonTitle size="large">Blank</IonTitle>
</IonToolbar>
</IonHeader>
<IonButton onClick={()=>{setUser({isSubscribed: false, name: "Pete"}); console.log( clicked! , user); setThing({title: "Mrs", nickname:"Morales"})}}>
Change Name
</IonButton>
<ExploreContainer />
</IonContent>
</IonPage>
);
};
export default Home;
Here in 住宅区 I have a button that when I push it I expect it to change the user.name to "Pete" and the Thing.nickname to "Morales" as can be displayed in the component.
when I click the button. Only thing.nickname changes from Morale to Morales. (Thing is something I set up all on the 住宅区 page). However user.name stays the same as "You" (user is something I set up on 应用。 and context.tsx.) Therefore, I think I am doing something wrong with using context. Any ideas as to what I m doing wrong?