我遇到了一个问题。
当我想做重定向时,我收到此错误
您尝试重定向到当前所在的同一路线:“/”
我的 App.js 文件如下所示
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>
);
}
如果我的代码对您来说不清楚 - 请帮助我提供任何建议。如果 !auth.isAuthentificated === true
,我如何将用户从任何路由重定向到 LoginPage
组件
我正在使用 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>
);
}
关于javascript - 如何正确使用 React 路由器重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164758/