您的位置:首页 > Web前端 > React

React生命周期调用函数介绍

2017-06-06 09:19 465 查看
React生命周期调用函数介绍
var MainComponent = React.createClass({//设置数据的默认值getDefaultProps: function () {console.log("getDefaultProps");return {name: 'null'};}//在组件加载之前调用一次,返回值作为this.state的初始值, getInitialState: function () {console.log("getInitialState");return {count: 0};},//在完成首次渲染之前调用componentWillMount: function () {console.log("componentWillMount");},//必选的方法,创建虚拟DOM//只能通过this.state和this.props访问数据//可以返回null,false或任何React组件//只能出现一个顶级组件(不能返回数组)//不能改变组件的状态//不能修改DOM的输出//一、render:function () {console.log("render");return <div>MainComponent</div>},//二、render: ()=> {console.log("render");return <div>MainComponent</div>},//    真实的DOM被渲染出来后调用,在该方法中可通过this.getDOMNode()访问到真实的DOM元素componentDidMount: function () {console.log("componentDidMount");},//    组件接收到新的props时调用,并将其作为参数nextProps使用componentWillReceiveProps: function (nextProps) {console.log("componentWillReceiveProps");if (nextProps.bool) {this.setState({bool: true});}},//组件是否需要渲染新的props或state,返回false表示跳过后续的生命周期方法,通常不需要使用,以免出现bugshouldComponentUpdate: function () {return true;},//接受到新的props或者state后,进行渲染之前调用componentWillUpdate: function () {console.log("componentWillUpdate");},//    完成渲染新的props或者state调用,此时可以访问到新的DOM元素componentDidUpdate: function () {console.log("componentDidUpdate");}//组件被移除之前调用,可以做一些清理工作,在conponentDidMount方法中添加的所有任务都需要在该方法中撤销, componentWillUnmount: function () {console.log("componentWillUnmount");}});ReactDOM.render(<MainComponent/>, document.getElementById("content"));

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: