comparing state and prop value - error: cannot read property 'state' of undefined
comparing state and prop value - error: cannot read property 'state' of undefined
我有两个数组(一个在状态中,一个是道具)并且都有 key:value 对
如果我使用:
this.props.test.col.forEach(function(element){
console.log(element.header);
}
我将在我的 prop
中看到 key:value 对数组中所有 header 值的列表
如果我使用:
console.log(this.state.gridOptions.api.blahhhh.hasOwnProperty('example header');
如果我所在州的 key:value 对之一的键是 'example header'
,它将 return 为真
两者都按预期工作。我想比较状态和道具 key:value 对,并在每次我的状态 key:value 对中的键与道具 key:value 对的值匹配时执行一个动作。
为什么下面的方法不起作用?我所做的就是将两者结合起来
this.props.test.col.forEach(function(element){
if (this.state.gridOptions.api.blahhhh.hasOwnProperty(element.header)){
console.log('hi');
}
}
我收到错误:
Uncaught TypeError: Cannot read property 'state' of undefined
在上面的示例代码中,如果 state 和 prop 的值和键匹配,则打印 'hi' 到控制台
在 forEach 回调中使用 'this.' 将有另一个上下文。
让我们试试:
let self=this;
this.props.test.col.forEach(function(element){
if (self.state.gridOptions.api.blahhhh.hasOwnProperty(element.header)){
console.log('hi');
}
}
我有两个数组(一个在状态中,一个是道具)并且都有 key:value 对
如果我使用:
this.props.test.col.forEach(function(element){
console.log(element.header);
}
我将在我的 prop
中看到 key:value 对数组中所有 header 值的列表如果我使用:
console.log(this.state.gridOptions.api.blahhhh.hasOwnProperty('example header');
如果我所在州的 key:value 对之一的键是 'example header'
,它将 return 为真两者都按预期工作。我想比较状态和道具 key:value 对,并在每次我的状态 key:value 对中的键与道具 key:value 对的值匹配时执行一个动作。
为什么下面的方法不起作用?我所做的就是将两者结合起来
this.props.test.col.forEach(function(element){
if (this.state.gridOptions.api.blahhhh.hasOwnProperty(element.header)){
console.log('hi');
}
}
我收到错误:
Uncaught TypeError: Cannot read property 'state' of undefined
在上面的示例代码中,如果 state 和 prop 的值和键匹配,则打印 'hi' 到控制台
在 forEach 回调中使用 'this.' 将有另一个上下文。
让我们试试:
let self=this;
this.props.test.col.forEach(function(element){
if (self.state.gridOptions.api.blahhhh.hasOwnProperty(element.header)){
console.log('hi');
}
}