[英]How to redirect to home in react router dom after login with redux?
I wrote a reducer and a action for authentication in redux, and check if user logged in with: 我在redux中编写了一个reducer和用于身份验证的操作,并检查用户是否使用以下方式登录:
const mapStateToProps = state => {
return {
isLoggedIn: state.auth.token !== null,
}
}
it works, and i can check user auth in redner with: 它有效,我可以使用以下方法检查redner中的用户身份验证:
if (this.props.isLoggedIn) {
console.log('logged in');
}
After login get logged in
in browser console. 登录后得到
logged in
在浏览器控制台。 How can i redirect to /
? 我如何重定向到
/
?
I try many way like: 我尝试了很多方法,例如:
if (this.props.isLoggedIn) {
this.props.history.push('/');
}
Browser url changed but page content doesn't change. 浏览器网址已更改,但页面内容未更改。
Update: My App.js routes: 更新:我的App.js路由:
<div className="App">
<Switch>
<Route path="/login" exact component={Login} />
<Route path="/" component={Template} />
</Switch>
</div>
Update2: my template: Update2:我的模板:
import React, { Component } from 'react';
class Template extends Component {
render() {
return (
<h1>Template</h1>
)
}
}
export default Template;
In render method 在渲染方法中
if (this.props.isLoggedIn) {
return <Redirect to='/'/>;
}
I guess you have to import the below. 我想您必须导入以下内容。
import { Redirect } from 'react-router-dom'
Is this what you are looking for? 这是你想要的?
make your routes like this 使你的路线像这样
<Switch>
<Route exact path="/login" exact component={Login} />
<Route path="/" component={Template} />
</Switch>
and then in your Login
component's render method 然后在您的
Login
组件的render方法中
this.props.isLoggedIn ? <Redirect to='/'/> : <div> { /* Login component stuff goes here */ } </div>
<Route exact path="/" component={Template} />
read more about exact 阅读更多关于确切
tend to put your root route first inside <Switch>
and for the last one you can have a route that will render in 404 cases. 倾向于将根路由放在
<Switch>
内,最后一个可以在404种情况下呈现。
from one of my projects 来自我的一个项目
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/auth' component={Auth} />
<Route path='/dashboard' component={Dahsboard} />
<Route component={Route404} />
</Switch>
</BrowserRouter>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.