Javascript 如何从获取请求内部引用函数和状态
我在代码中发现了错误,我调用的函数超出了我的获取承诺,这导致应用程序在更新用户搜索列表时有时无法更新。所以在最后的.then函数中,我不确定如何引用这个.importantfunction(this.importantarguments),就像我通常在fetch请求之外引用它们一样。在这种格式中,它们会导致未定义Javascript 如何从获取请求内部引用函数和状态,javascript,fetch,state,Javascript,Fetch,State,我在代码中发现了错误,我调用的函数超出了我的获取承诺,这导致应用程序在更新用户搜索列表时有时无法更新。所以在最后的.then函数中,我不确定如何引用这个.importantfunction(this.importantarguments),就像我通常在fetch请求之外引用它们一样。在这种格式中,它们会导致未定义 sendfriendrequest = (e, friend) => { console.log("You want to be friends with: "
sendfriendrequest = (e, friend) => {
console.log("You want to be friends with: " + friend);
let thetitleofsomeonewewanttobecloseto = friend;
let username = this.state.username;
fetch(currentrooturl + 'users/requestfriendship', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'same-origin',
body: JSON.stringify({
thetitleofsomeonewewanttobecloseto, username
})
})
.then(function(response) {
// You parse the data into a useable format using `.json()`
return response.json();
})
.then(function(data) {
// `data` is the parsed version of the JSON returned from the above endpoint.
// console.log("data: " + data); // { "userId": 1, "id": 1, "title": "...", "body": "..." }
console.log(data);
return data;
})
.catch(error => { console.log(error);
})
.then(function(data) {
this.limitedsearch(this.state.username, this.state.searchusers[0].length);
})
e.preventDefault(console.log(thetitleofsomeonewewanttobecloseto));
// research users to update list
// this.limitedsearch(this.state.username, this.state.searchusers[0].length);
}
在使用fetch函数之前,您可以存储对
this
的引用,然后在then()
中使用该引用
sendFriendRequest = (e, friend) => {
/* some code here */
let self = this; // Reference to this
fetch(/* some function arguments here */)
/* some then()s here */
.then(function(data) {
self.limitedsearch(self.state.username, self.state.searchusers[0].length);
self = null; // Destroy reference to avoid memory leaks
})
};
在使用fetch函数之前,您可以存储对
this
的引用,然后在then()
中使用该引用
sendFriendRequest = (e, friend) => {
/* some code here */
let self = this; // Reference to this
fetch(/* some function arguments here */)
/* some then()s here */
.then(function(data) {
self.limitedsearch(self.state.username, self.state.searchusers[0].length);
self = null; // Destroy reference to avoid memory leaks
})
};
您可以使用promise处理程序来避免重新定义此:
fetch().then((data) => {
this.limitedsearch(this.state.username, this.state.searchusers[0].length);
});
注意(data)=>{}
语法
使用箭头函数,不会重新定义此
。相反,它将被设置为与父上下文中的this
相同的值,为您提供所需的功能
诚然,这个
可能是一个令人困惑的话题。我建议阅读关键字以进一步理解主题。您可以使用promise处理程序来避免重新定义此:
fetch().then((data) => {
this.limitedsearch(this.state.username, this.state.searchusers[0].length);
});
注意(data)=>{}
语法
使用箭头函数,不会重新定义此
。相反,它将被设置为与父上下文中的this
相同的值,为您提供所需的功能
诚然,这个
可能是一个令人困惑的话题。我建议你仔细阅读这个关键词,以便进一步理解这个主题。谢谢你,这是非常有用的信息。我本可以使用箭头函数,但这是一个有趣的技术。谢谢,这是非常有用的。我本可以使用箭头函数,但这是一个有趣的使用技巧谢谢,这消除了我对箭头函数的混淆现在我更好地理解了它们的用法。谢谢,这消除了我对箭头函数的混淆现在我更好地理解了它们的用法。