componentWillReceiveProps在状态改变时被调用

ReactJS: componentWillReceiveProps is called on state change?

本文关键字:调用 改变 状态 componentWillReceiveProps      更新时间:2023-09-26

我试图解决一个场景,其中父将包括一个模块,当一个按钮被点击父,模块将出现。

现在,在模块中将有一个关闭按钮,点击它将隐藏模块。下次单击父按钮时,模块应该再次出现,依此类推。

目前代码:

var Parent = React.createClass({
  getInitialState(){
    return{
      showModule: false
    };
  },
  render(){
    return(
        <div className="parent" onClick={this._showModule}>
          Click me to show module
          <Module show={this.state.showModule}/>
        </div>
    );
  },
  _showModule(){
    this.setState({
      showModule: true
    });
  }
});
var Module = React.createClass({
  getInitialState(){
    return{
      show: this.props.show
    };
  },
  componentWillReceiveProps(nextProps){
    console.log('componentWillReceiveProps is called');
    this.setState({
      show: nextProps.show
    });
  },
  render(){
    return(
      (this.state.show?
        <div className="module" onClick={this._hide}>
          Click me and I will disappear myself
        </div> : null
      )
    );
  },
  _hide(){
    this.setState({
      show: false
    });  
  }
});

这里的问题是,每当我调用Module中的hide函数(它通过改变状态来隐藏自己)。show to false), componentWillReceiveProps被调用。

不应该只在Parent传递新props时调用吗?子模块中的状态变化如何以及为什么会调用componentWillReceiveProps?

JsBin http://jsbin.com/cunuci/edit?js、控制台、输出

当你点击" click me and I will disappear myself"你实际上点击了Parent并调用Parent。_showModule处理程序。把

<div className="parent" onClick={this._showModule}>
  Click me to show module
  <Module show={this.state.showModule}/>
</div>

<div className="parent">
   <p onClick={this._showModule}>Click me to show module</p>
   <Module show={this.state.showModule}/>
</div>

http://jsbin.com/naloxafile/1/edit?js、控制台、输出