问题描述
我的仪表板使用受保护的路由,我只希望登录的人能够看到仪表板。所以,在我的登录组件中,我正在获取数据,这是我检查用户的电子邮件和密码是否正确的地方。所以我想要做的是将一个布尔变量发送到 index.js 的父元素,并根据我想向用户显示仪表板的值。 所以这是我的 index.js:
const hist = createbrowserHistory();
console.log(hist)
ReactDOM.render(
<Router history={hist}>
<Switch>
<Route path="/" component={Login} exact />
<ProtectedRoute path="/admin" component={(props) => <AdminLayout {...props} />} isAuth={true}/>
<Route path="" component={() => "404 NOT FOUND"} />
</Switch>
</Router>,document.getElementById("root")
);
所以我想发送一个变量来检查,而不是里面的true,isAuth={true}。 还有我的登录组件:
const Login = ({ submitForm }) => {
const [isSubmitted,setIsSubmitted] = useState(false);
function submitForm() {
setIsSubmitted(true);
}
const { handleChange,values,handleSubmit,errors } = useForm(
submitForm,validate
);
const [loading,setLoading] = useState(false);
const [error,setError] = useState(false);
const [login,setLogin] = useState(false);
const fetchLogin = async (email,password) => {
try {
setLoading(true);
const res = await Axios({
data: {
user_email: email,user_password: password,},});
if (res.status === 200) {
setLogin(true);
localStorage.setItem("user-info",JSON.stringify(res));
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
function loginButton() {
fetchLogin(values.email,values.password);
}
return (
<form>
</form>
);
};
export default Login;
非常感谢您的帮助...
解决方法
有不同的方法。
- 您可以在
user-info
中读取从localStroage
检索ProtectedRoute
。在这种情况下,Login
除了localStorage.setItem("user-info",JSON.stringify(res))
之外不需要做任何事情
- 您可以使用回调函数将登录状态传播到父组件。有关示例,请参阅 this question。
- 如果您还想从其他组件访问登录状态,您可以考虑使用 React Context。 Here 就是一个例子。