Sop*_*ice 5 javascript reactjs react-router react-router-v4 react-router-dom
我有一个使用react-router-v4的应用程序。我有一个匹配的页面,除非您登录,否则无法访问。当用户未登录并尝试访问时,/match他们会被重定向到/login. 我的问题是,当用户重定向到/loginURL时,该 URL 保持为 /match。这在我的代码中的其他地方引起了问题。当用户被重定向到时,如何让 React-Router 更新 URL /login?我正在从 App.js 中的交换机重定向页面。这是我的代码的示例:
<Route
path='/match'
component= {
() => {
if (this.state.auth) return <HomePage />;
else return <LoginPage />;
}
}
/>
Run Code Online (Sandbox Code Playgroud)
TL; 博士
我怎样才能得到的URL变化/login,如果用户没有试图访问时登录/match。
您可能对 React Router 的工作原理有一些误解。在您的示例中,React Router 可以正常工作,因为您只是渲染组件。
您应该使用 React Router 的<Redirect />组件将用户重定向到新的 url。
您可以使用此示例代码实现您想要的行为。
<Route
path='/match'
render={
() => {
if(this.state.auth) return <HomePage />
return <Redirect to="/login" />
}
}
/>
<Route match="login" component={Login} />
Run Code Online (Sandbox Code Playgroud)
您还可以通过在组件内使用 React Router 提供的 prop 以编程方式在组件内实现相同类型的行为props.history.push('/login')。