import React, { Component } from "react";
import axios from 'axios';
class box extends Component {
constructor(props) {
super(props);
this.state = {
code: '',
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ [event.target.id]: event.target.value });
}
handleSubmit(event) {
axios.post('http://localhost:8080/validateCode', {
"access code": this.state.code,
})
.then(function (response) {
if(response.status === 200) {
this.props.history.push("/Treasure");
}
})
.catch(function (error) {
console.log(error);
});
event.preventDefault();
}
render() {
return (
<div>
<h1>page 1</h1>
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input id="code" type="text" value={this.state.code} onChange={this.handleChange} /> <br></br>
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default box;
如果给我一个给出响应状态为200的有效代码,则会出现以下错误
TypeError: Cannot read property 'props' of undefined
我想要将我重定向到/ Treasure端点。
它对我有其他作用,但对此我不知道。如果我要删除axios位并单击“提交”,它将按需要重定向我,但由于某些原因,它对此将不起作用
尝试为axios响应处理程序使用箭头函数代替function
,以保留this
的上下文。将function() {}
用作处理程序时,this
不再引用组件类,这将阻止您访问state
,props
或类似内容。箭头函数() => {}
将有助于保留this
的上下文:
handleSubmit(event) {
axios.post('http://localhost:8080/validateCode', {
"access code": this.state.code,
})
.then((response) => {
if(response.status === 200) {
this.props.history.push("/Treasure");
}
})
.catch((error) => {
console.log(error);
});
event.preventDefault();
}
希望有帮助!
handleSubmit = (event)=> {
axios.post('http://localhost:8080/validateCode', {
"access code": this.state.code,
})
.then( (response) => {
if(response.status === 200) {
this.props.history.push("/Treasure");
}
})
.catch( (error) => {
console.log(error);
});
event.preventDefault();
}
将您的Function更改为ES6,因为无法访问此实例,或者您可以在构造函数中绑定Function
this.handleSubmit = this.handleSubmit.bind(this)