【问题标题】:Sending object to firebase using dynamic key value使用动态键值将对象发送到 Firebase
【发布时间】:2020-08-23 13:41:59
【问题描述】:

我有一个表格组件,我用它来显示我的应用程序中所有其他组件的信息。这意味着当我发送数据时,我不能使用以下内容:

db.collection(collectionName).add({
  key1: val1,
  key2: val2,
  etc...
})

因为键可能会根据使用表的组件而有所不同。我曾考虑过使用 .map() 或 forEach 来遍历每个键,但我不断收到语法错误。

我最初以为我可以只发送对象 new_row 但这似乎无法正常工作。

这是我的表格组件:

class Table extends Component {
constructor(props){
    super(props);
    this.state = {
        rows: null,
        temprows: null,
        newrow: null,
        parent: this.props.tableComponent
    }
}
    addRow = function(){
      var new_rows = [...this.state.rows];
      new_rows.push(this.state.newrow);
      var new_row = JSON.parse(JSON.stringify(new_rows[0]));

      Object.keys(new_row).forEach(function(index) {
        new_row[index] = '';
      });

      db.collection(collectionNAame).add({
         I want to add the data here
      })

      this.setState({
        rows: new_rows,
        newrow: new_row
      });
}

对于这种特定情况,除了 .add 之外还有其他更好的方法吗?

【问题讨论】:

  • 你要传递给 .add 什么?
  • 这就是我想要弄清楚的。我原本以为我可以将 new_row 放入 .add() 中,但没有奏效。

标签: reactjs firebase firebase-realtime-database google-cloud-firestore


【解决方案1】:

在 db.collection .add 方法中,传播并传递 this.state.newrow 并在 then 块中更新您的状态。同样在你的addRow 函数中,new_row 应该从状态中获取(而不是new_rows[0]

像这样

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rows: null,
      temprows: null,
      newrow: {},
      parent: this.props.tableComponent
    };
  }
  addRow = function() {
    var new_rows = [...this.state.rows];
    new_rows.push(this.state.newrow);
    //   var new_row = JSON.parse(JSON.stringify(new_rows[0]));
    var new_row = { ...this.state.newrow };

    db.collection(collectionNAame)
      .add({
        ...this.state.new_row
      })
      .then(() => {
        Object.keys(new_row).forEach(function(index) {
          new_row[index] = "";
        });
        this.setState({
          rows: new_rows,
          newrow: new_row
        });
      });
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多