簡體   English   中英

使用Redux登錄后如何在React Router dom中重定向到首頁?

[英]How to redirect to home in react router dom after login with redux?

我在redux中編寫了一個reducer和用於身份驗證的操作,並檢查用戶是否使用以下方式登錄:

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

它有效,我可以使用以下方法檢查redner中的用戶身份驗證:

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;

在渲染方法中

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

我想您必須導入以下內容。

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

這是你想要的?

使你的路線像這樣

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

然后在您的Login組件的render方法中

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

閱讀更多關於確切

傾向於將根路由放在<Switch>內,最后一個可以在404種情況下呈現。

來自我的一個項目

<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM