【发布时间】:2021-05-19 17:18:35
【问题描述】:
我在 App.js 中创建了一个用户上下文,然后我使用 context.provider 将上下文值提供给子组件。 我可以简单地使用“login.js”组件中的上下文,但是当我尝试从另一个组件中使用它时,它会给出“未定义”的值。
这是我的 App.js
import React, {createContext} from "react";
export const UserContext = createContext();
function App() {
const [loggedUser, setLoggedUser] = React.useState({});
const changeUserValue = (newValue)=>{
setLoggedUser(newValue);
}
return (
<Router>
<Switch>
<UserContext.Provider value={{loggedUser,changeUserValue}}>
<Route path="/" exact>
{loggedUser.username ? <Home /> : <Login />}
</Route >
<Route path="/home" exact>
{loggedUser.username ?
<Home />
:
<Login />}
</Route >
</UserContext.Provider>
</Switch >
<Footer />
</Router >
);
}
这是我在 Login.jsx 中使用上下文的第一个组件
import React, {useContext} from "react";
import UserContext from "../../App.js"
function Login(props) {
const {changeUserValue}= useContext(UserContext);
...
Axios(config)
.then(function(response) {
if(response.status===200){
changeUserValue(response.data);
localStorage.setItem("myUser", JSON.stringify(response.data));
}
})
.catch(function(error) {
setErrors([{code:"Credintials", text:error.message}])
});
这是另一个组件“AdminControl.jsx”,它在使用上下文时给出“未定义”值:
import React, {useContext} from "react";
import UserContext from "../../App.js"
function AdminControls(props){
const {user}=useContext(UserContext);
console.log(user);
...
请记住,最后一个组件是该组件的子组件。
【问题讨论】:
标签: reactjs react-hooks use-context