【问题标题】:Writing to Firebase DB using redux action writes whole new data in the DB使用 redux 操作写入 Firebase DB 会在 DB 中写入全新数据
【发布时间】:2019-05-10 18:09:13
【问题描述】:

我正在尝试在 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"

【问题讨论】:

  • 你在哪里调度动作?
  • @RahulRana 你在哪里是什么意思?
  • @RahulRana 啊...我明白你的意思了。我有一个错误的操作文件,我以为我删除了,这个文件被导入到我的组件中。现在可以了。谢谢!
  • @RahulRana 不知何故,一个已删除的文件在退出应用程序之前仍然存在,所以直到 Ctrl-C 并重新运行应用程序时我才收到错误。
  • @RahulRana 删除的文件包含 notesRef.set(newNote) 这就是它设置整个数据库的原因。

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


【解决方案1】:

那么,firebase 的“设置”功能是用新数据替换现有数据。使用'update'函数更新数据库。

//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);
 };

快乐编码:)

【讨论】:

  • 我认为这里使用 set 方法没有什么问题。如果是这种情况,它也不应该在没有 redux 操作的情况下工作。通过操作使用更新方法时也不起作用。
【解决方案2】:

基本规则是设置覆盖和更新特定于每个节点。请改用更新。您还可以使用 push 让 firebase 自动生成唯一的节点名称:

设置:

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

更新:

同时写入一个节点的特定子节点 覆盖其他子节点,使用 update() 方法。

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

【讨论】:

  • 我已经尝试过更新方法,但效果完全一样。
  • 您确定更新的级别正确吗?如果您在包含其他节点的更高级别进行更新,则可能会覆盖这些节点。
  • 我删除了一个路径错误的文件。但是该文件仍然被应用程序识别,因为我删除文件后没有将其关闭。我想我必须在删除文件时重新启动应用程序以防万一。
猜你喜欢
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2019-04-20
  • 2011-07-21
  • 1970-01-01
相关资源
最近更新 更多