React子组件道具未更新

时间:2015-08-13 18:58:23

标签: javascript reactjs

我尝试将组件渲染Counter给其componentDidMount上的另一个组件Panel。我还将名为count的状态作为道具传递给Counter。在某个时间间隔内,我会更新状态。但问题是Counter的道具没有更新。道具仍然是初始值。是什么原因?

/** @jsx React.DOM */

var Panel = React.createClass({

  getInitialState: function(){
    return {
      count: 0
    }
  },

  tick: function() {
    setInterval(function(that) {
      that.setState({
        count: that.state.count + 1
      });
    }, 500, this);
  },

  componentDidMount: function() {
    var panel = React.findDOMNode(this.refs.panel);
    React.render(<Counter count={this.state.count}/>, panel);
    this.tick();
  },

  render: function(){
    return <div ref="panel"></div>;
  }

});

var Counter = React.createClass({

  render: function() {
    return <p>{this.props.count}</p>
  }

});

React.render(<Panel/>, document.getElementById('container'));



<body>
  <div id="container"></div>
</body>

我想知道此代码无效的原因

JS Bin check here

1 个答案:

答案 0 :(得分:1)

这段代码是香蕉。为什么要在组件内调用React.render?只需在render函数中渲染计数器。

/** @jsx React.DOM */

var Panel = React.createClass({

  getInitialState: function(){
    return {
      count: 0
    }
  },

  tick: function() {
    setInterval(function(that) {
      that.setState({
        count: that.state.count + 1
      });
    }, 500, this);
  },
  componentDidMount() {
    this.tick();
  },
  render: function(){
    return <div ref="panel"><Counter count={this.state.count}/></div>;
  }

});

var Counter = React.createClass({

  render: function() {
    return <p>{this.props.count}</p>
  }

});

React.render(<Panel/>, document.getElementById('container'));