无法读取未定义的属性“”(反应)?
2020-10-16
64
我尝试过绑定,但什么都没改变,现在我没主意了。哪怕是最小的提示也会有很大帮助。谢谢!
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);
}
});
}
2个回答
如果您使用的是
箭头函数
,则无需
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);
}
});
}
Jax-p
2020-10-16
同样,您需要绑定您的方法:
this.handleSubmit3 = handleSubmit3.bind(this);
还将定义更改为函数而不是箭头函数。
function handleSubmit3(e) {
...
}
您可以在 此处
阅读有关箭头函数的限制和用例的更多信息Aadil Mehraj
2020-10-16