2017-08-30 89 views
0

我正在構建一個登錄系統 - 當用戶填寫表單時 - 我創建了一個用於「驗證」用戶的redux動作 - 所以當this.props .authData.isLogged爲真 - 我想要調用導航功能以將用戶彈回到主頁。但是,this.props.router是不確定的?但我已經定義了與路由器?Reactjs/Redux - this.props.router undefined

import React, { Component } from 'react' 
//import { render } from 'react-dom' 
//import { withRouter } from 'react-router-dom' 
import { withRouter } from 'react-router'; 

// components 
import { connect } from 'react-redux'; 
import { bindActionCreators } from 'redux'; 
import { fetchAuthentication } from '../../actions/authAction'; 

import LoginSyncValidationForm from './LoginSyncValidationForm' 


// this is a class because it needs state 
class Login extends Component { 

    constructor(props, context) { 
    super(props, context); 
    this.submit = this.submit.bind(this); 
    } 

    componentDidMount() {  
    // console.log('this', this) 
    } 

    submit (data) { 
    this.props.fetchAuthentication(data); 
    } 

    navigate() { 
    console.log("navigate", this) 
    //this.props.router.push('/home'); 
    } 

    render() { 
    console.log(this.props.authData) 

    if(this.props.authData.isLogged){ 
     this.navigate(); 
    } 

    return (
     <div className="Page"> 
     <h2>Login</h2> 
     <LoginSyncValidationForm onSubmit={this.submit} /> 
     </div> 
    ) 
    } 
} 


function mapStateToProps(state) { 
    return { 
    authData: state.auth 
    }; 
} 

function mapDispatchToProps(dispatch) { 
return bindActionCreators({ fetchAuthentication }, dispatch); 
} 


const {object} = React.PropTypes 
Login.propTypes = { 
    router: object 
} 
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Login)) 
+0

https://stackoverflow.com/questions/39174814/using-react-router-withrouter –

+0

我試圖定義道具類型更早 - 它仍然沒有露面。 –

+0

可能重複[編程導航使用反應路由器](https://stackoverflow.com/questions/44127739/programatically-navigate-using-react-router) –

回答

1

可否請你嘗試了這一點。在React路由器V4中,API已經改變了很多,不能像以前那樣使用browserHistory.push()。現在您可以訪問組件內道具中的歷史對象。調用歷史對象的推入方法會將新條目推入歷史堆棧。

navigate() { 
    this.props.history.push('/home'); 
    } 
+0

工作 - 不知道爲什麼 –

+0

答案更新了描述。 –

+0

欣賞如果您可以將其標記爲答案,如果它有幫助。 –

0

您可以使用Redirect組件,像這樣:

import { Redirect } from 'react-router' 

... 
navigate() { 
    return <Redirect to="/home" /> 
} 
+0

沒有錯誤 - 但沒有重定向。 –

+0

什麼是react-router版本? –

+0

「react-router-dom」:「^ 4.2.2」, –