上下文.提供商到链路反应路由器



我试图为";CCD_ 1";的react路由器重定向到组件,但它只接收默认上下文。

我该如何解决这个问题?我正在使用react路由器v6

Context.js

import { createContext } from "react";
const UserContext = createContext(null);
export { UserContext };

App.js

return (
<UserContext.Provider value={{ teams, groupMatches, getImg }}>
<>
<div id="page-top">
<Router>
<Routes>
<Route path="/login" element={<Login />} />
<Route exact path={`/`} element={<Masthead />} />
</Routes>
</Router>
</div>
</>
</UserContext.Provider>

刊头.js

const { teams, groupMatches, getImg } = useContext(UserContext);
return userLogged && groupMatches ? (
<>
<UserContext.Provider
value={{
id: userLogged.id,
userInfo: userLogged,
teams,
groupMatches,
getImg,
}}
>
<Navigation       
/>
</UserContext.Provider>

Navigation.js

const { id, userInfo, teams, groupMatches, getImg } = useContext(UserContext);
<UserContext.Provider
value={{
id: userLogged.id,
userInfo: userLogged,
teams,
groupMatches,
getImg,
}}
>
<Link to="/pronosticos"><a className="nav-link" /*href="#services"*/>Pronosticos</a> </Link>
</UserContext.Provider>

基本上,由于在组件上使用了上下文提供程序,因此可以在代码中的任何位置访问它。您不应该在其他组件上使用用户上下文提供程序。

您应该知道的是,即使在Navigation组件中使用context.proprovider包装Link组件,Pronosticos组件也无法获取其值,因为该组件实际上没有使用上下文提供程序包装。因此,它将获得应用程序上下文提供者的值。

因此,请删除除应用程序外的所有组件上的所有上下文提供程序。并将id和userInfo值添加到应用程序上下文提供程序中。接下来,在Mashead组件的useEffect挂钩中,可以更改上下文值。

最新更新