2017-06-06 75 views
2

我使用像this類似的代碼在我的應用程序將用戶重定向登錄後的代碼如下所示:陣營路由器V4使用聲明重定向勿使電流分量

import React, { Component } from 'react' 
import { Redirect } from 'react-router' 

export default class LoginForm extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     fireRedirect: false 
    } 
    } 

    submitForm = (e) => { 
    e.preventDefault() 
    //if login success 
    this.setState({ fireRedirect: true }) 
    } 

    render() { 
    const { from } = this.props.location.state || '/' 
    const { fireRedirect } = this.state 

    return (
     <div> 
     <form onSubmit={this.submitForm}> 
      <button type="submit">Submit</button> 
     </form> 
     {fireRedirect && (
      <Redirect to={from || '/home'}/> 
     )} 
     </div> 
    ) 

    } 
} 

工作正常時,成功登錄已被觸發。但是有這種情況,即登錄用戶進入登錄頁面,應自動重定向到「主頁」頁面(或任何其他頁面)。

如何在不呈現當前組件的情況下使用重定向組件(並且據我瞭解discouraged)必須推送歷史記錄(例如,在componentWillMount中)?

+1

您正在使用錯誤的方法。重定向不應該在組件內單獨使用。相反,您必須將您的組件與「重定向」一起放入「路由」中。請參閱[官方文檔](https://reacttraining.com/react-router/web/api/Redirect)中的示例。 – hindmost

+0

謝謝,是的,我的方法有點不對。我現在已將我的所有路由和重定向到我的路由器中定義。 – Jankapunkt

回答

6

解決方案1 ​​

你可以使用withRouter HOC通過道具來訪問歷史。

導入路由器。

import { 
    withRouter 
} from 'react-router-dom'; 

然後用HOC包裹。

// Example code 
export default withRouter(connect(...)(Component) 

現在您可以訪問this.props.history。與componentWillMount()一起使用。

componentWillMount() { 
    const { history } = this.props; 

    if (this.props.authenticated) { 
    history.push('/private-route'); 
    } 
} 

溶液2好得多

這裏是例如在reacttraining

這將完全適合你。

但是你只需要創建LoginRoute來處理你描述的問題。

const LoginRoute = ({ component: Component, ...rest }) => (
    <Route 
    {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
     <Redirect to={{ 
      pathname: '/private-route', 
      state: { from: props.location } 
     }} /> 
    ) : (
     <Component {...props} /> 
    ) 
)} /> 
); 

和內部<Router />只需更換

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

<LoginRoute path="/login" component={Login}/> 

現在每次有人會嘗試訪問/login航作爲身份驗證的用戶,他將被重定向到/private-route。這是更好的解決方案,因爲如果不滿足條件,它不會安裝LoginComponent

+0

解決方案2似乎是我正在尋找的!現在檢查出來。 – Jankapunkt

+0

它絕對有效,我在我的項目中使用這種方法。讓我知道你是否需要幫助。 – loelsonk

+0

解決方案2的工作原理非常完美,我可以在組件中刪除路由邏輯。非常感謝! – Jankapunkt