【发布时间】:2019-01-30 02:20:33
【问题描述】:
我正在学习反应,所以我创建了一个简单的应用程序来管理带有标题和描述的笔记。
该应用程序与使用 Go 制作的 REST API 进行通信,因此我可以获取、编辑、创建和删除笔记。
所以,问题如下,我有这两个功能来删除和编辑笔记,它们在 App.js 文件中:
removeNote(note) {
fetch('http://localhost:9000/notes/delete', {
mode: 'cors',
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(note)
}).then(res => {
console.log(res.text);
this.getNotes();
})
}
saveEditNote(note) {
fetch('http://localhost:9000/notes/update', {
mode: 'cors',
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(note)
}).then(res => {
console.log(res);
this.getNotes();
})
}
功能不同,但是两个函数做的差不多,都是向后端发送一个http请求,得到响应后调用this.getNotes();函数更新笔记列表。
现在,当我按下“删除”按钮时,应用程序成功删除了笔记,并调用 getNotes() 来更新列表就好了。
当我按下“保存”按钮更新笔记时,应用程序成功更新了笔记,但是,当它调用 getNotes() 时出现以下错误
未处理的拒绝(TypeError):_this4.getNotes 不是函数
问题: 为什么它在编辑功能中失败,但在删除功能中却像一个魅力?
我已经像这样在 App.js 中绑定了函数:
this.getNotes = this.getNotes.bind(this);
所以这应该不是问题。
注意组件标签代码:
cards = this.state.notes.map((note, i) => {
return (
<Note note={note} index={i} onRemoveNote={this.removeNote} onEditNote={this.saveEditNote} key={i}></Note>
)
})
Note组件handleSaveEditNote功能代码:
handleSaveEditNote(note) {
note.name = this.state.noteName;
note.description = this.state.noteDescription;
this.props.onEditNote(note)
}
我通过从 Note.js 调用 App.js 中的 getNotes 函数然后刷新页面窗口来解决问题。
getNotes() {
this.props.onGetNotes();
window.location.reload();
}
但它很难看,我应该能够在编辑功能中使用 getNotes 功能,就像我在删除功能中使用它一样。
任何帮助将不胜感激,感谢您的时间并为糟糕的英语道歉。祝你有美好的一天!
【问题讨论】:
-
您需要在构造函数中手动绑定 saveEditNote 函数,例如 this.saveEditNote = this.saveEditNote.bind(this);或者将saveEditNote改成箭头功能解决问题
-
removeNote()中的this不会自动绑定到组件,因此this.getNodes()将不起作用。您需要使它们成为箭头函数或在contructor中使用bind()。 -
组件上每个在其主体中使用
this的函数都需要绑定。
标签: javascript reactjs