如何使用重新基础将syncState同步到firebase?

时间:2017-10-18 05:34:12

标签: reactjs firebase

我正在尝试使用重新基础来保存数据但是通过这种设置,我什么都没得到。当我尝试There were 31 warnings (use warnings() to see them) >xy$z [1] 0 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 时,我没有错误,也没有新对象。

我的重新设置在这里:

addExpense

如果我没有使用componentDidMount,那么我的addExpense操作就像这样,一切运行良好:

class ExpensesContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expenses: {
        expenseList: []
      }
    }
  }

  componentDidMount(){
    base.syncState(`/`, {
      context: this,
      state: 'expenses.expenseList',
      asArray: true
    });
  }

  addExpense = (expense) => {
    this.setState({
      expenses: this.state.expenses.expenseList.concat([expense]) //updates Firebase and the local state
    });
  }

2 个答案:

答案 0 :(得分:1)

expenses: this.state.expenses.expenseList.concat([expense])

在你传递错误值的.setState()方法上,最后看起来应该是{ expenses: [<list here>] },而应该是:

expenses: { expenseList: this.state.expenses.expenseList.concat([expense])}

re-base不仅适用于.concat()(通过阅读文档,我也是同样的)

这就是说,你只需要.setState()预期的变量,它应该更新。

答案 1 :(得分:0)

如果有人遇到类似的问题 - 这个解决方案对我有用:

class ExpensesContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
        expenseList: []
    }
  }

  componentDidMount(){
    base.syncState(`/expenses`, {
      context: this,
      state: 'expenseList',
      asArray: true
    });
  }

  deleteExpense = (expenseToRemove) => {
    const expenseList = [...this.state.expenseList].filter((expense) => {
      return expenseToRemove !== expense.uid;
    });
    this.props.history.push("/expenses");
    this.setState({expenseList});
  }

  addExpense = (expense) => {
    this.setState({
      expenseList: this.state.expenseList.concat([expense]) 
    });
    this.props.history.push("/");
  }