嗨,我正在请求请求后使用React Router,但遇到了一些问题。
handleSubmit = event => {
event.preventDefault();
request.post(
{
url: 'http://localhost:8080/usernamepassword',
json: true,
body: {
email: this.state.email,
password: this.state.password
}
},
function(err, httpResponse, body) {
console.log(err);
console.log(httpResponse);
console.log(body);
if (err) {
this.props.history.push('/nosuccess');
} else {
this.props.history.push('/success');
}
}
);
问题出在
if (err) {
this.props.history.push('/nosuccess');
} else {
this.props.history.push('/success');
}
我知道(至少我认为)问题与this.props无关。
完整代码如下。我正在将请求放入箭头函数(来自@webdevdani)。立即学习。
import React, {Component} from 'react';
import request from 'request';
import {Link, withRouter} from 'react-router-dom';
import '../Form.css';
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
}
handleChange = event => {
this.setState({
[event.target.id]: event.target.value
});
};
handleSubmit = event => {
event.preventDefault();
request.post(
{
url: 'http://localhost:8080/signin',
json: true,
body: {
username: this.state.username,
password: this.state.password
}
},
function (err, httpResponse, body) {
console.log(err);
console.log(httpResponse);
console.log(body);
if (err) {
this.props.history.push('/nosuccess');
} else {
this.props.history.push('/success');
}
}
);
};
render() {
return (
<div>
<form id="login" className="form-content" onSubmit={this.handleSubmit}>
<h1 className="form-content-text-h1"> Sign In</h1>
<div className="padding10">
<div className="form-content-text-textbox"> EDIPI (DoD ID):</div>
<input type="text" className="input1" id="username" onChange={this.handleChange} required/>
<br/>
<br/>
<div className="form-content-text-textbox"> Password:</div>
<input type="password" className="input1" id="password" onChange={this.handleChange} required/>
</div>
<button type="submit" className="button1">
Sign In
</button>
<br/>
<Link to="/resetpassword" style={{textDecorationColor: '#26c6da'}}>
<h1 className="form-content-link-text">Sign In Assistance</h1>
</Link>
<br/>
<br/>
<h1 className="form-content-text-h1"> New Users </h1>
<Link to="/register">
<button className="button1" type="submit">
Register
</button>
</Link>
</form>
</div>
);
}
}
export default withRouter(SignIn);
这是完整的代码。
答案 0 :(得分:1)
看起来'this'的值不是您所期望的。如果将request.post
参数中的函数声明更改为箭头函数,则它的组件值应为'this'。然后,您将可以访问this.props