无法读取未定义(反应)的属性?



我试过绑定,但它没有改变任何东西,现在我没有主意了。最小的提示都会有很大的帮助。非常感谢。

export default class Login extends React.Component {

constructor(props) {
super(props);
this.state = {
persons: [],
name: '',
password: '',
}
this.handleSubmit3 = this.handleSubmit3.bind(this);
}

和错误位置(成功函数中的setstate(:无法读取未定义的属性"persons">

handleSubmit3 = event => {
event.preventDefault();
var user = this.state.name + '$' + this.state.password;

$.ajax({
url: 'https://localhost:44348/api/user/LoginUserCheckPassword',
type: 'POST',
data: JSON.stringify(user),
contentType: 'application/json',
dataType: 'json',
async: false,
success: function (data) {
this.setState({persons: this.state.persons, name: this.state.name, password: data});  //error here
},
error: function (jQXHR, textStatus, errorThrown) {
console.log("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}

}); 
}

如果使用arrow functions,则不需要bind。你可以在上阅读更多关于它的信息。你能在箭头函数中绑定"this"吗?问题

问题是success: function (data)既没有绑定,也没有绑定箭头函数。这意味着this引用的是成功函数,而不是类。使用箭头函数success: (data) => {}应该可以解决您的问题。

类似这样的东西:

handleSubmit3 = event => {
event.preventDefault();
var user = this.state.name + '$' + this.state.password;
$.ajax({
url: 'https://localhost:44348/api/user/LoginUserCheckPassword',
type: 'POST',
data: JSON.stringify(user),
contentType: 'application/json',
dataType: 'json',
async: false,
success: (data) => {
this.setState({persons: this.state.persons, name: this.state.name, password: data});  //error here
},
error: (jQXHR, textStatus, errorThrown) => {
console.log("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
});
}

您需要绑定您的方法,同样:

this.handleSubmit3 = handleSubmit3.bind(this);

同时将定义更改为函数,而不是箭头函数。

function handleSubmit3(e) {
...
}

你可以在这里阅读更多关于箭头功能的限制和用例

最新更新