Reactjs 当在循环中时,this.state不是对象
我在一个函数中有以下函数,我试图检查一个对象的状态。问题是,当我运行代码时,它告诉我this.state不是一个对象Reactjs 当在循环中时,this.state不是对象,reactjs,react-native,this,Reactjs,React Native,This,我在一个函数中有以下函数,我试图检查一个对象的状态。问题是,当我运行代码时,它告诉我this.state不是一个对象 convertNeighbourArrayIntoMap(neighbourData) { var neighbourCategoryMap = {}; // Create the blank map neighbourData.forEach(function(neighbourItem) { if(this.sta
convertNeighbourArrayIntoMap(neighbourData) {
var neighbourCategoryMap = {}; // Create the blank map
neighbourData.forEach(function(neighbourItem) {
if(this.state.searchString == ""){
console.log("No Search String");
}
if (!neighbourCategoryMap[neighbourItem.category]) {
// Create an entry in the map for the category if it hasn't yet been created
neighbourCategoryMap[neighbourItem.category] = [];
}
neighbourCategoryMap[neighbourItem.category].push(neighbourItem);
});
return neighbourCategoryMap;
}
这是可行的,但我需要它在循环中
convertNeighbourArrayIntoMap(neighbourData) {
var neighbourCategoryMap = {}; // Create the blank map
if(this.state.searchString == ""){
console.log("No Search String");
}
neighbourData.forEach(function(neighbourItem) {
if (!neighbourCategoryMap[neighbourItem.category]) {
// Create an entry in the map for the category if it hasn't yet been created
neighbourCategoryMap[neighbourItem.category] = [];
}
neighbourCategoryMap[neighbourItem.category].push(neighbourItem);
});
return neighbourCategoryMap;
}
使用箭头功能按预期保留
此上下文:
neighbourData.forEach((neighbourItem) => {
...
if (!this.state.searchString.length) {
console.log("No Search String");
}
...
使用箭头功能按预期保留此上下文:
neighbourData.forEach((neighbourItem) => {
...
if (!this.state.searchString.length) {
console.log("No Search String");
}
...
这是因为forEach
的回调没有拾取相同的上下文。轻松修复切换到箭头功能(如果可能):
如果没有可用的箭头函数,则bind
forEach
函数:
neighbourData.forEach(function(neighbourItem) {
if(this.state.searchString == ""){
console.log("No Search String");
}
if (!neighbourCategoryMap[neighbourItem.category]) {
// Create an entry in the map for the category if it hasn't yet been created
neighbourCategoryMap[neighbourItem.category] = [];
}
neighbourCategoryMap[neighbourItem.category].push(neighbourItem);
}.bind(this));
这是因为forEach
的回调没有拾取相同的上下文。轻松修复切换到箭头功能(如果可能):
如果没有可用的箭头函数,则bind
forEach
函数:
neighbourData.forEach(function(neighbourItem) {
if(this.state.searchString == ""){
console.log("No Search String");
}
if (!neighbourCategoryMap[neighbourItem.category]) {
// Create an entry in the map for the category if it hasn't yet been created
neighbourCategoryMap[neighbourItem.category] = [];
}
neighbourCategoryMap[neighbourItem.category].push(neighbourItem);
}.bind(this));