【发布时间】:2018-08-31 07:15:37
【问题描述】:
我的 React Router V4 路由结构是这样的:
const isAuthenticated = () => {
let hasToken = localStorage.getItem("jwtToken");
if (hasToken) return true;
return false;
};
const AuthenticatedRoute = ({ component: Component, ...rest }) =>
<Route
{...rest}
render={props =>
isAuthenticated()
? <Component {...props} />
: <I NEED TO REDIRECT FROM HERE TO SERVER PAGE />}
/>;
class App extends Component {
render() {
return (
<BrowserRouter basename="/editor">
<Switch>
<AuthenticatedRoute exact path="/" component={AppNav} />
<AuthenticatedRoute
exact
path="/:module"
component={AppNav}
/>
<AuthenticatedRoute
exact
path="/:module/:screen"
component={AppNav}
/>
<AuthenticatedRoute
exact
path="/:module/:screen/:action"
component={AppNav}
/>
<AuthenticatedRoute
exact
path="/:module/:screen/:action/:id"
component={AppNav}
/>
<Route component={PageNotFoundError} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
正如您在代码中看到的,如果未通过身份验证,我想重定向到服务器页面。该页面是另一个管理用户注册的反应应用程序,位于服务器中,但在另一个路由树中:/registration
我尝试过的没有成功:
<Redirect to="//registration' />
windows.location = "/registration"
windows.location.href = "/registration"
<Redirect to="http//registration' />
windows.location = "http://registration"
windows.location.href = "http://registration"
所有重定向到当前应用程序中的页面。
解决办法是什么?
【问题讨论】:
-
尽量提供完整的网址,例如
window.location="https://your_website.com/your/server/path" -
试过了。不工作。
-
您有任何错误吗?并确保它是
window而不是windows -
感谢指正。确实是
window。没有错误。移动到localhost:/editor/registration或localhost:/editor/https://registration。不会离开 App 的 React 路由器。 -
首先尝试
<Redirect to="/registration" />。也许首先检查令牌并在渲染之后放置它更容易:if (!hasToken) return <Redirect to='/registration' />;和之后放置
标签: reactjs routes react-router-v4