2017-08-02 108 views
1

我想在登錄後重定向到用戶頁面。這是我的代碼:用react-redux登錄後重定向到用戶頁面

import React, {PropTypes} from 'react'; 
import styles from '../styles/login.scss'; 
import { connect } from 'react-redux'; 
import { checkLogin } from './../actions/login.action'; 

class Login extends React.Component { 
constructor(props) { 
    super(props); 
    this.state = { 
     username: '', 
     password: '' 
    }; 
    this.handleChangeUsername = this.handleChangeUsername.bind(this); 
    this.handleChangePassword = this.handleChangePassword.bind(this); 
} 

componentWillReceiveProps(nextProps) { 
    if (nextProps.wasSuccessful !== this.props.wasSuccessful) { 
     this.redirectToUserPage(nextProps.wasSuccessful); 
    } 
} 

redirectToUserPage =() => { 
    if (this.props.wasSuccessful) { 
     window.location.href = 'localhost:3000/filterableTable'; 
    } 
}; 

login =() => { 
    this.props.dispatch(checkLogin(this.state)); 
}; 
handleChangeUsername(event) { 
    this.setState({username: event.target.value}); 
} 
handleChangePassword(event) { 
    this.setState({password: event.target.value}); 
} 
render() { 
    console.log('----', this.props.wasSuccessful); 
    return (
    <div className={styles.loginForm}> 
    <h3>Welcome</h3> 
    <div className={styles.container}> 
     <label><b>Username</b></label> 
     <input type="text" value={this.state.username} onChange={this.handleChangeUsername} name="username" placeholder="Username" required></input> 

     <label><b>Password</b></label> 
     <input type="password" value={this.state.password} onChange={this.handleChangePassword} name="password" placeholder="Password" required></input> 
     <input type="submit" value="Login" onClick={this.login}></input> 
    </div> 
    </div> 
); 
} 
} 

Login.propTypes = { 
    login: PropTypes.func.isRequired, 
    dispatch: PropTypes.func.isRequired, 
    wasSuccessful: PropTypes.boolean, 
}; 

export default connect((state) => ({ 
    wasSuccessful: state.login.wasSuccessful 
}))(Login); 

在wassuccessful狀態改變爲True,所以當我按登錄時,我應該能夠重定向到用戶頁面。

componentWillReceiveProps(nextProps) { 
     if (nextProps.wasSuccessful !== this.props.wasSuccessful) { 
       this.redirectToUserPage(nextProps.wasSuccessful); 
     } 
    } 

我明白,當狀態發生改變,這將被調用,所以在這裏我所說的功能redirectToUserPage。

redirectToUserPage =() => { 
     if (this.props.wasSuccessful) { 
      window.location.href = 'localhost:3000/filterableTable'; 
     } 
}; 

我試過這樣,但它不起作用。請幫助〜

+0

假設你正在使用的反應路由器,看到這個https://stackoverflow.com/questions/44127739/programatically-navigate-using-react -router/44128108#44128108 –

回答

0

我建議從我的經驗hashHistory

import {hashHistory} from 'react-router' 

    redirectToUserPage =() => { 
     if (this.props.wasSuccessful) { 
      hashHistory.push('#/filterableTable'); 
     } 
}; 
相關問題