【问题标题】:Syncing state between React app and Firebase databaseReact 应用程序和 Firebase 数据库之间的同步状态
【发布时间】:2016-09-13 10:28:49
【问题描述】:

我是 React 新手,我正在学习在线教程。我已经开发了下面的代码作为 Todo 应用程序的一部分。这是从状态中删除现有待办事项(对象)的逻辑。状态格式如下:

todos: {todo1: 'Throw the keyboard out of the window',
        todo2: 'Go and buy a new keyboard'}

...这是我的应用程序的关键代码:

var TodoApp = React.createClass({
  getInitialState: function() {
    return {
      todos: {}
    };
  },
  removeTodo: function(key) {
    var todosCopy = Object.assign({}, this.state.todos);
    delete todosCopy[key];

    this.setState({
      todos: {...todosCopy}
    });
  }  
}  

以上内容完成了工作,当调用removeTodo 方法时,确实删除了选定的待办事项。

当讲师通过 npm re-base library 将应用与 Firebase 数据库链接时出现问题,这样如果用户已经使用过该应用,todos 状态将被预先填充。

他通过在TodoApp 中添加以下方法来做到这一点:

componentDidMount: function() {
  var base = Rebase.createClass('https://example-com.firebaseio.com/');
  base.syncState('todos', {
    context: this,
    state: 'todos',
  });

一旦添加了上述内容,我的removeTodo 方法就会停止更新状态。但讲师实际上让他的应用程序与他自己版本的removeTodo 方法一起工作如下:

removeTodo : function(key) {
  this.state.todos[key] = null;
  this.setState({
    todos : this.state.todos
  });
},

我认为他没有遵循最佳实践,因为我们不应该根据React docs 改变状态。我宁愿避免这种情况。所以我的问题是:

  1. 为什么他的removeTodo 版本有效而​​我的无效?
  2. 我该怎么做才能让它发挥作用?

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    通过以下列方式重构我的 removeTodo 方法,我成功地避免了状态变化并在 React 应用和 Firebase 数据库之间成功同步状态:

    removeTodo: function(key) {  
      this.setState({
        todos: {[key]: null}
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      相关资源
      最近更新 更多