Reactjs 使用react redux登录后重定向到用户页面
我试图在登录后重定向到用户页面。这是我的代码:Reactjs 使用react redux登录后重定向到用户页面,reactjs,redux,Reactjs,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 { construct
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);
我知道当状态改变时会调用它,所以在这里我调用函数redirectToUserPage
redirectToUserPage = () => {
if (this.props.wasSuccessful) {
window.location.href = 'localhost:3000/filterableTable';
}
};
我试着这样做,但没用。请帮忙~根据我的经验,我建议
import {hashHistory} from 'react-router'
redirectToUserPage = () => {
if (this.props.wasSuccessful) {
hashHistory.push('#/filterableTable');
}
};
我敢肯定,由于redirectToUserPage中的
this.props.wassuctive
,您会遇到控制台错误(类似于“无法访问未定义的wassuctive”)。您没有将此绑定到构造函数中的redirectToUserPage函数。此操作的范围已从Login类更改为redirectToUserPage。该函数中的此
没有道具。假设您使用的是react路由器,请参见此
import {hashHistory} from 'react-router'
redirectToUserPage = () => {
if (this.props.wasSuccessful) {
hashHistory.push('#/filterableTable');
}
};