目前我正在使用 react 构建一个小项目。最近我设法理解了 useContext
钩子并且它工作正常,但是每次刷新页面时,所有使用上下文数据都消失了。
我知道发生这种情况是因为我正在 App.js 顶部初始化 useContext
值(见下文),这是我使用 react 路由器拥有所有视图路由的地方。因此,我想请教您关于防止这种情况发生的最佳方法的建议。
App.js
export default function App() {
const [user, setUser] = useState(null);
const providerValue = useMemo(() => ({user,setUser}), [user,setUser]);
return (
<Router>
<UserContext.Provider value = {providerValue}>
<div>
<Header />
<Container fluid className="p-0">
<Row className="no-gutters">
<Col xs="2">
<Sidebar />
</Col>
<Col xs="10">
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/users/logout">
<Logout />
</Route>
<Route path="/users/login">
<Login />
</Route>
<Route path="/users/create">
<UserAdd />
</Route>
<Route path="/users/:id/edit">
<UsersEdit />
</Route>
<Route path="/users/:id">
<UsersView />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/covid">
<ShowChart />
</Route>
<Route path = "/messages/choosedestination/:id">
<MessageForm />
</Route>
<Route path="/messages/choosedestination">
<ChooseDestination />
</Route>
<Route path= "/messages/getmessage/:id">
<AAAA />
</Route>
<Route path="/messages/:id">
<ShowMessage />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Col>
</Row>
</Container>
</div>
</UserContext.Provider>
</Router>
);
}