import React from 'react';
import ReactDOM from 'react-dom';

 

//子类

class SayHello2 extends React.Component{
constructor(props){
super(props);
this.state=({
word:""
})
}
componentWillReceiveProps(){
console.log("componentWillReceiveProps clalled")
}
shouldComponentUpdate(){
console.log("shouldComponentUpdate called")
return true;
}
componentWillUpdate(){
console.log("componentWillUpdate called")
}
//this.setState 进入shouldComponentUpdate
//this.forceUpdate 进入componentWillUpdate
handleClick(){
  this.setState({
    word:'word changed'
  })
 或 this.state.word="word change";
   this.forceUpdate();
}
render(){
return <div>{this.state.word}{this.props.name}
<button onClick={this.handleClick.bind(this)}>改变state</button>

</div>
}
}

//父类
class SayHello3 extends React.Component{
constructor(props){
super(props);
this.state=({
word2:'word2'
})
this.handleClick = this.handleClick.bind(this);
}
componentWillMount(){
console.log("componentWillMount called")
}
componentDidMount(){
console.log("componentDidMount called")
}
componentWillUnmount(){
console.log("componentWillUnmount called")
}
componentUnmountEvent(){
ReactDOM.render(
<h1>SayHello3 moved</h1>,
document.getElementById("root3")
)
}
handleClick(){
this.setState({
word2:'word2 changed'
})
}
render(){
return <h1>
hello <SayHello2 name={this.state.word2}></SayHello2>----父类中调用子类
<button onClick={this.handleClick}>改变word2</button>
<button onClick={this.componentUnmountEvent.bind(this)}>移除</button>
</h1>
}
}
ReactDOM.render(
<SayHello3 name="qq11111221" word="word"/>,
document.getElementById("root3")
)

1、父类调用子类 参数变化的时候(本例中是点击“改变word2”),先调用子类中componentWillReceiveProps(),然后调用shouldComponentUpdate(),shouldComponentUpdate()返回的是true 在调用componentWillUpdate()

2、通过this.setState({})修改变量值(本例中点击“改变state”),先调用shouldComponentUpdate(),然后调用componentWillUpdate()

3、通过this.forceUpdate() 修改变量,直接调用componentWillUpdate()