用redux登录后,如何在反应路由器dom中重定向到home?

问题描述 投票:0回答:3

我在redux中写了一个reducer和一个身份验证操作,并检查用户是否登录:

const mapStateToProps = state => {
    return {
        isLoggedIn: state.auth.token !== null,
    }
}

它工作,我可以检查渲染中的用户身份验证:

if (this.props.isLoggedIn) {
    console.log('logged in');
}

登录后在浏览器控制台中获取logged in。我怎样才能重定向到/

我尝试了很多方式:

if (this.props.isLoggedIn) {
    this.props.history.push('/');
}

浏览器网址已更改,但网页内容未更改。

更新:我的App.js路线:

  <div className="App">
    <Switch>
      <Route path="/login" exact component={Login} />
      <Route path="/" component={Template} />
    </Switch>
  </div>

Update2:我的模板:

import React, { Component } from 'react';
class Template extends Component {
    render() {
           return (
            <h1>Template</h1>
        )
    }
}
export default Template;
javascript reactjs redux react-router-dom
3个回答
0
投票

在渲染方法中

if (this.props.isLoggedIn) {
   return <Redirect to='/'/>;
}

我想你必须导入下面的内容。

import { Redirect } from 'react-router-dom'

这是你想要的?


0
投票

让你的路线像这样

<Switch>
      <Route exact path="/login" exact component={Login} />
      <Route path="/" component={Template} />
</Switch>

然后在你的Login组件的渲染方法中

this.props.isLoggedIn ? <Redirect to='/'/> : <div> { /* Login component stuff goes here */ } </div> 

-1
投票
<Route exact path="/" component={Template} />

了解更多关于exact的信息

倾向于将你的根路线放在<Switch>的第一个位置,而对于最后一个,你可以有一个在404个案例中渲染的路线。

来自我的一个项目

<BrowserRouter>
    <Switch>
      <Route exact path='/' component={Home} />
      <Route path='/auth' component={Auth} />
      <Route path='/dashboard' component={Dahsboard} />
      <Route component={Route404} />
    </Switch>
</BrowserRouter>
© www.soinside.com 2019 - 2024. All rights reserved.