javascript - 如何正确使用 React 路由器重定向?
问题描述
我遇到了一个问题。当我想做重定向时收到此错误
我的App.js文件如下所示
You tried to redirect to the same route you're currently on: "/"
render() {
const { auth } = this.props;
if (!auth.isAuthentificated) {
return <Redirect to="/" />;
}
return (
...
<Switch>
<Route path="/welcome" component={Welcome} />
<Route path="/user-info" component={UserInfo} />
<Route path="/" component={LoginPage} />
</Switch>
);
}
如果我的代码对您来说不清楚 - 请帮助我提供任何建议。
如果我正在使用,我如何将用户从任何 Routs 重定向到LoginPage
组件!auth.isAuthentificated === true
react-router 4.2.0,
解决方案
在重定向到该路径之前,您需要验证您尚未位于该路径:
import {withRouter} from 'react-router-dom';
// ...
render() {
const { auth } = this.props;
const {pathname} = this.props.location;
if (!auth.isAuthentificated && pathName !== '/') {
return <Redirect to="/" />;
}
return (
...
<Switch>
<Route path="/welcome" component={Welcome} />
<Route path="/user-info" component={UserInfo} />
<Route path="/" component={LoginPage} />
</Switch>
);
}
推荐阅读
- devise - 用户名/密码和 sso 系统 - sso 用户的密码值应该是多少
- vbscript - 如何通过 VBscript 获取 CAD 零件的位置?
- if-statement - 如何将 WHERE 函数添加到复杂字符串
- angular - 使用 ngfor 时如何处理数据以更快地显示
- python - 列名减半,数据用 pyodbc 和 Teradata 数据库编码错误
- java - Log4J 2 配置:如何同时按大小和按天拆分日志文件?
- javascript - 在第二次点击时触发 jquery 事件更新输入
- json - DStream JSON 对象到 SQLite
- python - Python Subprocess.Popen 带有声音警报的通知
- html - 将图像添加到 html 标题而不是 favicon