我使用的是react router 4而不是react router 3,所以我使用的是react-router-dom。我试图让 this.props.history.push 工作,但它所做的只是保持视图相同,但 URL 发生了变化。
例如,我单击按钮,它调用一个函数,该函数只调用 this.props.history.push('/posts')。 URL 从 localhost:3000/signin 更改为 localhost:3000/posts。但我仍然处于登录视图中。
但是,如果我点击刷新,它将重定向到帖子页面。我查看了其他问题,这些人无论如何都无法将其转到那里,即使他们刷新或进入网址并按 Enter 键。
我将发布下面的代码来看看我做错了什么。另外,我使用的是 React router v4 而不是 3。我无法使用 browserHistory.push 和 v3 使用的其他东西。
Code:
成分:
import React, { Component } from 'react';
import {Field, reduxForm} from 'redux-form';
import {connect} from 'react-redux';
import * as actions from '../../actions';
import {withRouter} from 'react-router';
class Signin extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
renderField(field) {
const { meta: {touched, error} } = field;
const className = `form-group ${touched && error ? 'has-danger' : ''}`;
return (
<div className={className}>
<label><strong>{field.label}:</strong></label>
<input
className="form-control"
type={field.type}
{...field.input}
/>
<div className="text-help">
{ touched ? error : ''}
</div>
</div>
)
}
onSubmit({email, password}) {
// this.props.signinUser({email, password}, () => {
this.props.history.push('/posts');
// });
}
renderAlert() {
if(this.props.errorMessage) {
return (
<div className="alert alert-danger">
<strong>Oops</strong> {this.props.errorMessage}
</div>
)
}
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit)}>
<Field
label="Email"
name="email"
type="email"
component={this.renderField}
/>
<Field
label="Password"
name="password"
type="password"
component={this.renderField}
/>
{this.renderAlert()}
<button type="submit" className="btn btn-success">Sign In</button>
</form>
);
}
}
function validate(values) {
const errors = {};
//Validate the inputs from values
if(!values.email) {
errors.email = "Enter an email!";
}
if(!values.password) {
errors.password = "Enter a password!";
}
//If errors is empty, the form is fine to submit
//If errors has any properties, redux form assumes form is invalid
return errors;
}
function mapStateToProps(state) {
return {
errorMessage: state.auth.error
};
}
export default reduxForm({
validate,
form: 'signin'
})(connect(mapStateToProps, actions)(withRouter(Signin)));
action:
export function signinUser({email, password}, cb) {
return function(dispatch) {
axios.post(`${ROOT_URL}/signin`, {email, password})
.then((response) => {
dispatch({type: AUTH_USER});
localStorage.setItem('token', response.data.token);
})
.then(() => cb())
.catch((error) => {
dispatch(authError(error.response.data.error));
})
}
}