react之组件的生命周期

2017-09-01  本文已影响33人  小猿_Luck_Boy

生命周期的方法

void constructor(props)

组件的构造,我们可以再这里初始化数据,调用一次

void componentWillMount()

组件将要渲染,调用一次,在render调用之前

ReactElement render()

这个是组件最重要的,必须实现的且必须包含返回值,一般我们在这里返回我们的组件信息

void componentDidMount()

组件渲染完成 ,调用一次,在render调用之后

void componentDidUpdate(prpos,state)

组件更新完毕,接收prposstate新的参数,propsstate是新的传入对象,当组件更新完成调用,可多次调用
s
void componentWillReceiveProps(prpos)

父控件向子控件传值,组件将要收到新的值, 接收prpos新的参数,可多次调用

void componentWillUnmount()

组件卸载(webStorm会自动提示补全成componentWillUnMount,这是错误的),调用一次

bool shouldComponentUpdate(prpos,state)

组件是否重新绘制 接收prposstate新的参数,可多次调用

该方法是用来优化的react性能的,可以判断新的props和以前的props值是否发生改变来决定是否重新绘制组件

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>
    )
  }
}

运行结果

点击CustomButton,再点击更新,最后点击卸载的运行的日志如下

上一篇下一篇

猜你喜欢

热点阅读