【问题标题】:react component not updating state反应组件不更新状态
【发布时间】:2016-01-19 09:48:19
【问题描述】:

当我控制台记录它返回未定义的状态但在我的反应开发工具中我可以看到结果数组。 这是组件:

    var Categorias = React.createClass({
  getInitialState: function () {
    return {
      items: []
    };
  },

componentWillMount: function (){
  var  firebaseRef = new Firebase("https://rapifood.firebaseio.com/categorias");
  firebaseRef.on("child_added", function(dataSnapshot) {
    var items= [];
    items.push(dataSnapshot.val());
    this.setState({
      items: items
    });
  }.bind(this));
},

componentDidMount: function () {
  console.log(this.state.items);
},

我做错了什么?

【问题讨论】:

  • 您可能想尝试将console.log 放入渲染函数中。不确定在componentDidMount 被触发时数据是否已经存在

标签: reactjs firebase


【解决方案1】:

您可能想要另一个状态变量来跟踪加载状态:

var Categories = React.createClass({
  getInitialState: function () {
    return {
      loaded: false,
      items: []
    };
  },

  componentWillMount: function (){
    var  firebaseRef = new Firebase("https://rapifood.firebaseio.com/categorias");
    firebaseRef.on("child_added", function(dataSnapshot) {
      this.setState({
        loaded: true,
        items: this.state.items.concat(dataSnapshot.val())
      });
    }.bind(this));
  },

  componentWillUnmount: function() {
    // Don't forget to remove the Firebase subscription here.
  }

  render: function() {
    if (!this.state.loaded) {
      return <div>Loading...</div>;
    }
    // Now you can render the list of items here.
  },
});

【讨论】:

    【解决方案2】:

    这是因为您在 ajax 回调上设置状态,该回调在初始渲染 (componentDidMount) 之后完成。

    【讨论】:

    • 更好方法的示例?
    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 2021-05-19
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2021-01-27
    • 2021-10-08
    相关资源
    最近更新 更多