使用redux操作写入Firebase DB会在数据库中写入整个新数据

时间:2019-05-10 05:48:24

标签: reactjs firebase firebase-realtime-database react-redux

我正在尝试在React应用程序中写入Firebase DB。如果我使用数据库引用和设置方法,它将添加新的数据条目。但是,当我通过redux操作使用相同的方法时,它将写入全新的数据。

这是有效的代码。

      const notesRef = firebase.database().ref('notes');
      const noteRef = notesRef.child(this.state.noteId);

      const note = {
        text: this.state.text,
        timestamp: this.state.timestamp,
        title: this.titleTextArea.value,
      }

      noteRef.set(note);

这是动作

      export const addNote = (newNoteId, newNote) => async dispatch => {
            notesRef.child(newNoteId).set(newNote);
      };
      const note = {
        text: this.state.text,
        timestamp: this.state.timestamp,
        title: this.titleTextArea.value,
      }

      this.props.addNote(this.state.noteId, note);

不良结果:

notes: "a6ff48e4-f34a-483f-a639-b0dbfd703009"

好的结果:

notes:
      b85def67-3877-4d2f-b5c7-23d8295768ad
            text: "{\"ops\":[{\"insert\":\"fsasfs\\n\"}]}"
            timestamp: 1557467143056
            title: "asfa"

      e4290153-a40c-464f-a92a-39eded74bd2a
            text: "{\"ops\":[{\"insert\":\"sadfasdfsd\\n\"}]}"
            timestamp: 1557467154054
            title: "asdfsdaf"

2 个答案:

答案 0 :(得分:1)

因此,firebase的“设置”功能是用新数据替换现有数据。使用“更新”功能更新数据库。

//get new key
var newPostKey = firebase.database().ref().child(newNoteId).push().key;

//Update existing
 export const addNote = (newNoteId, newNote) => async dispatch => {
    let update = {}
    update[newPostKey] = newNote
    notesRef.update(update);
 };

快乐编码:)

答案 1 :(得分:1)

基本规则是“设置替代”,并且“更新”特定于每个节点。请改用更新。您还可以使用push使Firebase自动生成唯一的节点名称:

设置:

  

使用set()覆盖指定位置的数据,包括任何   子节点。

更新:

  

在没有节点的情况下同时写入节点的特定子节点   覆盖其他子节点,请使用update()方法。

https://firebase.google.com/docs/database/web/read-and-write https://firebase.google.com/docs/database/admin/save-data

相关问题