React - 设置状态以在表单中显示验证错误的消息会导致:无法读取未定义的属性'setState' - 为什么?



我有一个注册表单,从服务器端,我检查字段是否为空,如果是,那么我res.send("xxx"(,然后从fronend我想将状态设置为要显示的消息。使用我的代码(如下(我收到错误"无法读取未定义的属性'setState'",我不明白为什么?!谢谢!!

class Signup extends React.Component{
constructor(props) {
super(props)
this.state = {
firstnameVlidation:"",
lastnameVlidation:"",
firstname: '',
lastname: '',
}
this.registering = this.registering.bind(this);
}
}
registering(event) {
event.preventDefault();
var info = {
"firstname": this.state.firstname,
"lastname": this.state.lastname
...
}
axis.post('/signup', {info})
.then(function(res){
return res.data
})
.then(function(response){
if (response === 'no') {
this.setState({
firstnameVlidation:"Enter Firstname"
})
}
})
}
....

我的后端路由:

....
if (req.body.firstname.length<1){
res.send("no")
}
....

.then语句中的函数未绑定到 react 组件对象的上下文。您可以更改:

function(response) {
...
}

response => {
...
}

自动绑定此匿名函数,然后正确定义this

最新更新