我正在尝试在我的仪表板中实施受保护的路由器。所以我的登陆页面直接是一个登录页面,如果用户成功登录,我想将页面重定向到我的仪表板。所以这是我的 index.js:
ReactDOM.render(
<Router history={hist}>
<Switch>
<Route path="/" component={Login} exact />
<ProtectedRoute path="/admin" component={(props) => <Adminlayout {...props} />}/>
<Route path="" component={() => "404 NOT FOUND"} />
</Switch>
</Router>,document.getElementById("root")
);
所以我的登录组件非常基础,我在这里获取数据并检查用户是否存在于数据库中:
const Login = ({ submitForm },props) => {
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({
//API CALL
});
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);
auth.login(() => {
props.history.push("/admin");
});
}
return (
<form>
</form>
);
};
export default Login;
所以我有一个基本的 Auth 类:
class Auth {
constructor() {
this.authenticated = false;
}
login(cb) {
this.authenticated = true;
cb();
}
logout(cb) {
this.authenticated = false;
cb();
}
isAuthenticated() {
return this.authenticated;
}
}
export default new Auth();
这是我的受保护路由器:
export const ProtectedRoute = ({
component: Component,...rest
}) => {
return (
<Route
{...rest}
render={props => {
if (auth.isAuthenticated()) {
return <Component {...props} />;
} else {
return (
<Redirect
to={{
pathname: "/",state: {
from: props.location
}
}}
/>
);
}
}}
/>
);
};
所以一切看起来都很好,但是当我点击按钮提交时,我得到无法读取未定义的属性“推送”我真的不明白为什么我会得到它。
请查看我的代码并帮助我。 评论也是值得赞赏的。