我已经在构造函数中绑定了 removeNote 函数,但我仍然收到无法读取属性错误。
class Wall extends React.Component {
constructor(props) {
super(props);
this.state = {
noteDataArray: ['Note value 1 yay','2 notes']
};
this.removeNote = this.removeNote.bind(this);
}
saveNote(value, index) {
var temp = this.state.noteDataArray;
temp[index] = value;
this.setState({noteDataArray: temp});
}
removeNote(index) {
var temp = this.state.noteDataArray;
temp.splice(index, 1);
this.setState({noteDataArray: temp});
}
render() {
return (
<div className="Wall">
{this.state.noteDataArray.map(function (value, index) {
return (
<Notes key={index} index={index} removeit={this.removeNote} >
{value}
</Notes>
);
})}
</div>
)
}
}
当我在另一个组件中使用相同的绑定方法时,它可以工作。
您可能已经绑定了this.remove
但您在Array#map
中调用它,这会在其回调的每次迭代中创建自己的this
上下文。
Array#map
采用第二个参数,该参数将在每次迭代中用作this
。
按如下方式修改代码应该可以解决问题:
this.state.noteDataArray.map(function (value, index) {
return (
<Notes key={index} index={index} removeit={this.removeNote} >
{value}
</Notes>
);
}, this);
// ^---- add this as second argument
当您映射this.state.noteDataArray
时,请尝试使用箭头函数,如下所示:
{this.state.noteDataArray.map((value, index) => {
return (
<Notes key={index} index={index} removeit={this.removeNote} >
{value}
</Notes>
);
})}
看看 MDN 关于箭头函数的文章
在箭头函数之前,每个新函数都定义了自己的这个值......事实证明,这在面向对象的编程风格中很烦人。
箭头函数不会创建自己的 this 上下文,因此这在封闭上下文中具有其原始含义