我正在基于this tutorial.在React中构建一个应用程序
我使用的是较旧的方法,而不是使用更新的es2016,因此遇到了一些挑战。我在浏览器中收到此错误:“ TypeError:无法读取未定义的属性'props'”。我认为它指向{this.props.onDelete}部分。这是我的Notes.jsx组件代码片段:
var Notes = React.createClass({
render: function () {
return (
<ul>
{this.props.notes.map(
function(note) {
return (
<li key={note.id}>
<Note
onTheDelete={this.props.onDelete}
task={note.task} />
</li>
);
}
)}
</ul>
);
}
});
这是App.jsx的代码段,它是父代码:
var App = React.createClass({
getInitialState: function () {
return {
notes: [
{
id: uuid.v4(),
task: 'Learn React'
},
{
id: uuid.v4(),
task: 'Do laundry'
}
]
}
},
newNote: function () {
this.setState({
notes: this.state.notes.concat([{
id: uuid.v4(),
task: 'New task'
}])
});
},
deleteNote: function() {
return 'hi';
},
render: function () {
var {notes} = this.state;
return (
<div>
<button onClick={this.newNote}>+</button>
<Notes notes={notes} onDelete={this.deleteNote}/>
</div>
);
}
});
我从deleteNote中删除了实际上有用的部分,以确保那里没有问题。我在使用“ this”以及我在所提到的教程中进行的绑定工作时花了很多时间。
最佳答案
由于JS的工作原理,this
函数内部的map
与它外部的this
不同。
您可以保存this.props.onDelete
并在不使用道具参考的情况下使用它:
render: function () {
var onDelete = this.props.onDelete;
return (
<ul>
{this.props.notes.map(
function(note) {
return (
<li key={note.id}>
<Note
onTheDelete={onDelete}
task={note.task}
/>
</li>
);
}
)}
</ul>
);
}
无关,但我会将
map
函数移到其自身的函数中,并避免深度嵌套。