反应测试' componentWillReceiveProps'

时间:2016-04-11 21:50:55

标签: reactjs react-native

我是React.js的新手。在尝试理解React中的生命周期时,我偶然发现了componentWillReceiveProps。即使我掌握了其他功能,我仍然无法弄清楚componentWillReceiveProps。我创建了一个小片段,每按一次按钮,我就会增加变量' val'。当val变为5的倍数时,我想改变'增加'的值,这是我无法做到的。

我的代码是:

var Increment = React.createClass({
  getInitialState: function() {
    return {val: 0, increasing: false};
  },
  componentWillMount: function() {
    console.log("componentWillMount");
  },
  componentDidMount: function() {
    console.log("componentDidMount");
  },
  handleClick: function() {
    console.log("inHandleClick");
    console.log(this.state.val);
    this.setState({val: (this.state.val+1)});
  },
  componentWillReceiveProps : function(nextProps) {
    this.setState({
      increasing: (nextProps.val > this.props.val)
    });
  },
  shouldComponentUpdate: function(nextProps, nextState) {
    return (nextState.val % 5 ==0)
  },

  render: function() {
    console.log(this.state.increasing);
    return (
      <div>
        <button onClick={this.handleClick}>{this.state.val}</button>
      </div>
    );
  }
});


ReactDOM.render(<Increment />, mountNode);

任何潜在顾客?提前致谢

1 个答案:

答案 0 :(得分:1)

请参阅this fiddle

def double_list(x):
    for i in range(len(x)):
        x[i] = x[i] * 2
    return x
x = [3, 5, 7]
print double_list(x)

(感谢@Aaron以获得更准确的说明) 如果你的组件的道具被设置,则调用var IncrementButton = React.createClass({ componentWillReceiveProps : function(nextProps) { this.setState({ increasing: (nextProps.val > this.props.val) }); }, render: function() { return (<button onClick={this.props.handleClick}>{this.props.val}</button>); } }); var Increment = React.createClass({ getInitialState: function() { return {val: 0, increasing: false}; }, handleClick: function() { console.log("inHandleClick"); console.log(this.state.val); this.setState({val: (this.state.val+1)}); }, shouldComponentUpdate: function(nextProps, nextState) { return (nextState.val % 5 ==0) }, render: function() { console.log(this.state.increasing); return ( <div> <IncrementButton handleClick={this.handleClick} val={this.state.val}/> </div> ); } }); React.render(<Increment />, mountNode); ;请注意,即使道具的价值没有变化,也可能会调用它(您似乎考虑到了这一点而不是检查)。由于您要将新值的props与旧值进行比较,因此需要在组件外部管理状态。因此,在此示例中,我通过提取按钮将您的组件拆分为两个部分。

相关问题