首页 > 解决方案 > 反应 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>
);

}

感谢帮助。

标签: javascriptreactjsfirebasefirebase-realtime-database

解决方案


你应该这样做:

const newNotes = [...this.state.notes]
const newNode = {
  id: snap.key,
  noteContent: snap.val().noteContent,
}
newNotes.push(newNode)
this.setState({
     notes: newNotes,
});

你不能只是推送你需要用新数组替换节点数组。需要遵循不变性来告诉react to rerender


推荐阅读