gpt4 book ai didi

javascript - React - 未处理的拒绝(TypeError): _this4. getNotes 不是函数

转载 作者:行者123 更新时间:2023-11-28 14:23:39 25 4
gpt4 key购买 nike

我正在学习 React,因此我创建了一个简单的应用程序来管理带有标题和描述的笔记。

该应用程序与用 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() 时,我收到以下错误

Unhandled Rejection (TypeError): _this4.getNotes is not a function

问题:为什么它在编辑功能中失败,但在删除功能中却像 super 按钮一样有效?

我已经在 App.js 中绑定(bind)了该函数,如下所示:

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(note)removeNote(note) 函数怎么样?您是否像对 getNotes() 函数那样绑定(bind)它们?如果没有,请绑定(bind)它们或使用箭头函数来声明它们,如下所示: saveEditNote = note => {...}removeNote(note) 函数相同。希望能解决您的问题

关于javascript - React - 未处理的拒绝(TypeError): _this4. getNotes 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54426800/

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