生命周期的方法
void constructor(props)
組件的構(gòu)造,我們可以再這里初始化數(shù)據(jù),調(diào)用一次
void componentWillMount()
組件將要渲染,調(diào)用一次,在render調(diào)用之前
ReactElement render()
這個(gè)是組件最重要的,必須實(shí)現(xiàn)的且必須包含返回值,一般我們?cè)谶@里返回我們的組件信息
void componentDidMount()
組件渲染完成 ,調(diào)用一次,在render調(diào)用之后
void componentDidUpdate(prpos,state)
組件更新完畢,接收prpos和state新的參數(shù),props和state是新的傳入對(duì)象,當(dāng)組件更新完成調(diào)用,可多次調(diào)用
s
void componentWillReceiveProps(prpos)
父控件向子控件傳值,組件將要收到新的值, 接收prpos新的參數(shù),可多次調(diào)用
void componentWillUnmount()
組件卸載(webStorm會(huì)自動(dòng)提示補(bǔ)全成componentWillUnMount,這是錯(cuò)誤的),調(diào)用一次
bool shouldComponentUpdate(prpos,state)
組件是否重新繪制 接收prpos和state新的參數(shù),可多次調(diào)用
該方法是用來(lái)優(yōu)化的react性能的,可以判斷新的props和以前的props值是否發(fā)生改變來(lái)決定是否重新繪制組件
return true 重新繪制
return false 不重新繪制
例子
class CustomButton extends Component {
constructor(props){
super(props)
this.state = {
count:0
}
}
componentWillMount() {
console.log("componentWillMount")
}
componentDidMount() {
console.log("componentDidMount")
}
componentDidUpdate(nextProps, nextState) {
console.log("componentDidUpdate")
}
componentWillReceiveProps(props) {
console.log("componentWillReceiveProps",props);
}
componentWillUnmount() {
console.log("componentWillUnmount")
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate",nextProps);
return true;
}
onClick(){
this.setState(
{
count:++this.state.count
}
)
console.log("控件更新組件的props")
}
render(){
return(
<button onClick={()=>this.onClick()}>
{this.state.count}
</button>
)
}
}
class HelloState extends React.Component {
constructor(props) {
super(props);
this.state = {
loading:true,
update:""
};
}
click(){
console.log("卸載組件")
this.setState({loading:false})
}
update(){
console.log("父控件更新組件的props")
this.setState({update:"1"})
}
render (){
return (
<div>
<button onClick={this.click.bind(this)}>卸載</button>
<button onClick={this.update.bind(this)}>更新</button>
{this.state.loading ?<CustomButton update={this.state.update}/>:null
}
</div>
)
}
}
運(yùn)行結(jié)果
點(diǎn)擊CustomButton,再點(diǎn)擊更新,最后點(diǎn)擊卸載的運(yùn)行的日志如下
