React组件生命周期
组件的生命周期包含三个主要部分:
装载组件触发getInitialState
初始化 如果是使用 ES6 的语法,你也可以在构造函数中初始化状态,比如: class Counter extends Component { constructor(props) { super(props); this.state = { count: props.initialCount }; } render() { // ... } } getDefaultProps只在组件创建时调用一次并缓存返回的对象(即在 因为这个方法在实例初始化之前调用,所以在这个方法里面不能依赖 如果是使用 ES6 语法,可以直接定义 Counter.defaultProps = { initialCount: 0 }; componentWillMount()
render()组装生成这个组件的 componentDidMount()
更新组件触发componentWillReceiveProps(object nextProps)当一个挂载的组件接收到新的props的时候被调用。该方法应该用于比较 在初始化渲染的时候,该方法不会调用。 componentWillReceiveProps: function(nextProps) { this.setState({ likesIncreasing: nextProps.likeCount > this.props.likeCount }); } shouldComponentUpdate(object nextProps,object nextState): boolean当组件做出是否要更新DOM的决定的时候被调用。 在接收到新的 如果确定新的 shouldComponentUpdate: function(nextProps,nextState) { return nextProps.id !== this.props.id; } 如果 componentWillUpdate(object nextProps,object nextState)在更新发生之前被调用。你可以在这里调用 componentDidUpdate(object prevProps,object prevState)在更新发生之后调用。 卸载组件触发componentWillUnmount()在组件移除和销毁之前被调用。清理工作应该放在这里。比如无效的定时器,或者清除在 componentDidMount 中创建的 DOM 元素。 装载的方法getDOMNode()DOMElement可以在任何挂载的组件上面调用,用于获取一个指向它的渲染DOM节点的引用。 forceUpdate()当你知道一些很深的组件state已经改变了的时候,可以在该组件上面调用,而不是使用
var Button = React.createClass({ getInitialState: function() { return { data:0 }; },setNewNumber: function() { this.setState({data: this.state.data + 1}) },render: function () { return ( <div> <button onClick = {this.setNewNumber}>INCREMENT</button> <Content myNumber = {this.state.data}></Content> </div> ); } }) var Content = React.createClass({ componentWillMount:function() { console.log('Component WILL MOUNT!') },componentDidMount:function() { console.log('Component DID MOUNT!') },componentWillReceiveProps:function(newProps) { console.log('Component WILL RECIEVE PROPS!') },shouldComponentUpdate:function(newProps,newState) { return true; },componentWillUpdate:function(nextProps,nextState) { console.log('Component WILL UPDATE!'); },componentDidUpdate:function(prevProps,prevState) { console.log('Component DID UPDATE!') },componentWillUnmount:function() { console.log('Component WILL UNMOUNT!') },render: function () { return ( <div> <h3>{this.props.myNumber}</h3> </div> ); } }); ReactDOM.render( <div> <Button /> </div>,document.getElementById('example') ); 总结
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |