【发布时间】:2019-01-25 09:04:41
【问题描述】:
我目前在一个 React 项目中,我有一个使用令牌处理身份验证的后端,以及一个可以通过对服务器的异步调用来验证用户身份的反应前端。
这是我所拥有的:
- 首页
- 登录页面
- 注册页面
这是我想要实现的目标:
- 当用户走任何路线但未通过身份验证时 -> 重定向到登录页面
- 当用户登录时 -> 重定向到主页
我当前的代码:
App.js
class App extends Component {
render() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/register">Register</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/TodoList">Protected Page</Link>
</li>
</ul>
<Route path="/register" component={Register} />
<Route path="/login" component={Login} />
<PrivateRoute path="/TodoList" component={TodoList} />
</div>
</Router>
);
}
}
PrivateRoute.js
import { verifAuth } from "./verifAuth";
class PrivateRoute extends Component {
state = {
loading: true,
isAuthenticated: false
};
componentDidMount() {
verifAuth().then(isAuthenticated => {
this.setState({
loading: false,
isAuthenticated
});
});
}
render() {
const { component: Component, ...rest } = this.props;
if (this.state.loading) {
return <div>LOADING</div>;
} else {
return (
<Route
{...rest}
render={props => (
<div>
{!this.state.isAuthenticated && (
<Redirect
to={{
pathname: "/login",
state: { from: this.props.location }
}}
/>
)}
<Component {...this.props} />
</div>
)}
/>
);
}
}
}
verifAuth.js
export async function verifAuth() {
return await axios
.post("/auth", {
token: localStorage.getItem("token")
})
.then(res => {
if (res.status === 200) return true;
return false;
})
.catch(err => console.log(err));
}
从 login.js 重定向方法
const { from } = this.props.location.state || { from: { pathname: "/" } };
if (this.state.redirect) {
return <Redirect to={from} />;
}
【问题讨论】:
-
Tyler McGinnis 介绍了如何使用 react-router v4 进行设置:tylermcginnis.com/react-router-protected-routes-authentication
-
您好,我已按照本教程进行操作,但不幸的是,这不适用于真正的回调..
-
“不工作”并没有以任何人都可以帮助您的方式解释您的情况。分享你目前拥有的代码
-
感谢您的建议。我添加了我的代码并找到了我的方法不起作用的原因。其实 auth 功能都很好,就是这样:用户登录,然后被重定向到私有路由,但是私有路由之前的值是 'isAuthenticated' (false),所以它重定向到 /login .当我刷新页面时,我可以转到私有路由,因为值已更新。
标签: reactjs authentication react-router