gpt4 book ai didi

javascript - 我收到 Uncaught TypeError : Cannot read property 'removeNote' of undefined even after binding removeNote in the constructer

转载 作者:行者123 更新时间:2023-12-01 03:48:10 25 4
gpt4 key购买 nike

我已经在构造函数中绑定(bind)了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>
)
}
}

当我在另一个组件中使用相同的绑定(bind)方法时,它可以工作。

最佳答案

您可能已经绑定(bind)了 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

关于javascript - 我收到 Uncaught TypeError : Cannot read property 'removeNote' of undefined even after binding removeNote in the constructer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43432086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com