我在函数中有以下函数,我试图检查对象的状态。问题是,当我运行代码时,它告诉我this.state不是一个对象。
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;
}
答案 0 :(得分:3)
这是因为forEach
的回调没有获得相同的上下文。轻松修复它切换到箭头功能(如果可能):
neighbourData.forEach((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
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));
答案 1 :(得分:1)
使用箭头功能按预期保留this
上下文:
neighbourData.forEach((neighbourItem) => {
...
if (!this.state.searchString.length) {
console.log("No Search String");
}
...