javascript - 反应 this.setState 不更新我的值,火力变化正在显示
问题描述
我的代码有问题。我正在尝试在 react + fireabse 中做笔记。向 fireabse 添加注释并 setState 显示它们,但是如果我想更改注释的值,第二个 setState 不会更改它,但在 firebase 中注释会更改其值。
这是我的代码
constructor() {
super();
this.app = firebase.initializeApp(DB_CONFIG);
this.database = this.app.database().ref().child('notes');
this.state = {
notes: [],
};
}
componentDidMount() {
this.database.on('child_added', snap => {
this.state.notes.push(new Note(snap.key, snap.val().noteContent));
this.setState({
notes: this.state.notes
});
});
this.database.on('child_changed', snap => {
this.state.notes.forEach(note => {
if(snap.key === note.id) {
note.id = snap.key;
note.noteContent = snap.val().noteContent;
}
});
this.setState({
notes: this.state.notes,
});
});
}
addNote(note) {
this.database.push().set({
noteContent: note,
});
}
changeNote(id, note) {
this.database.child(id).update({
noteContent: note,
});
}
render() {
return (
<div>
<div> {
this.state.notes.map(note => {
return (
<NoteComponent noteContent={note.noteContent}
noteId={note.id}
key={note.id}
changeNote={this.changeNote.bind(this)}>
</NoteComponent>
)
})
}
</div>
<div>
</div>
<NoteFormComponent
addNote={this.addNote.bind(this)}>
</NoteFormComponent>
</div>
);
}
感谢帮助。
解决方案
你应该这样做:
const newNotes = [...this.state.notes]
const newNode = {
id: snap.key,
noteContent: snap.val().noteContent,
}
newNotes.push(newNode)
this.setState({
notes: newNotes,
});
你不能只是推送你需要用新数组替换节点数组。需要遵循不变性来告诉react to rerender
推荐阅读
- html - 如何在 div 中放置图像
- postgresql - postgresql pg_ctl 启动超时
- windows - 批处理脚本:\MyProg 此时出乎意料
- javascript - Javascript:Firefox 忽略 Date.toLocaleString 和 Intl.DateTimeFormat 中的 dateStyle 和 timeStyle 选项
- visual-studio-code - 如何让语言特定命令在 VSCode 中工作?
- android - 如何信任我的应用程序中的所有自签名证书
- postgresql - 如何通过使用 PyODBC 的 ODBC 连接使用“CREATE DATABASE”创建 PostgreSQL 数据库?
- php - 仅打印数组的一部分
- r - R:从 S4 方法中更改 S4 对象
- python - 是否有内置函数可以删除 Python 中的所有注册表项和子项?