gpt4 book ai didi

javascript - React Js类型错误: Cannot read property 'LoginAuth' of undefined

转载 作者:行者123 更新时间:2023-12-03 03:55:38 25 4
gpt4 key购买 nike

我想在完成数组映射后调用一个函数来检查与我的变量匹配的任何值,但我想在一个单独的函数中执行此操作,所以我尝试调用该函数,但收到错误 TypeError :无法读取未定义的属性“LoginAuth”

我的代码是这样的

LoginAuth = (Res) => {
if (this.username === this.state.Username) {
console.log("get to login auth and true");
} else {
console.log("Gets to login auth and false");
}
}
CheckLoginAuth() {
console.log("gets to check login auth");
console.log(this.state.AuthRes);
console.log("Username=" + this.state.Username);
console.log("Password=" + this.state.Password);
this.props.AuthRes.map(function (Res) {
console.log("ID=" + Res.id);
console.log("Username=" + Res.username);
console.log("Password=" + Res.password);
this.LoginAuth(Res);//react is actually throwing the error here.
})
}

为什么会出现错误,当我单击表单上的按钮时,它会被调用,该按钮可以正常工作,它只是这个新功能。

最佳答案

map 函数中的

this 不会转到您想要的 this,实际上是 未定义本身。

另外,正如人们在评论中所说,为什么不使用粗箭头呢?无需使用 function 调用,但如果您想保持这样,就这样。

试试这个:

通知:

var self = this;

并调用self.login...

LoginAuth = (Res) => {
if (this.username === this.state.Username) {
console.log("get to login auth and true");
} else {
console.log("Gets to login auth and false");
}
}
CheckLoginAuth() {
console.log("gets to check login auth");
console.log(this.state.AuthRes);
console.log("Username=" + this.state.Username);
console.log("Password=" + this.state.Password);
var self = this;
this.props.AuthRes.map(function (Res) {
console.log("ID=" + Res.id);
console.log("Username=" + Res.username);
console.log("Password=" + Res.password);
self.LoginAuth(Res);//react is actually throwing the error here.
})
}

关于javascript - React Js类型错误: Cannot read property 'LoginAuth' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44965849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com