精益 React 学习指南 (Lean React)- 1.4 React 组件生命周期和
1.4 React 组件生命周期
1.4.1 组件React 中组件有自己的生命周期方法,简单理解可以为组件从 出生(实例化) -> 激活 -> 销毁 生命周期 hook。通过这些 hook 方法可以自定义组件的特性。 除此之外,还可以设置一些额外的规格配置。
这些生命周期方法都可以在调用 React.createClass 的参数对象中传入, 我们已经使用过了一些方法:
1.4.2 mixins类型: mixins 可以理解为 React 的插件列表,通过这种模式在不同组件之间共享方法数据或者行为只需共享 mixin 就行,mixins 内定义的生命周期方法在组件的生命周期内都会被调用。 可能的一些疑问:
插件模式并非继承的模式,对于问题 1、2 的答案是一样的,都会被调用,调用顺序为 mixins 数组中的顺序。
eg: var MyMixin1 = { componentDidMount: function() { console.log('auto do something when component did mount'); } }; var MyMixin2 = { someMethod: function() { console.log('doSomething'); } }; var MyComponnet = React.createClass({ mixins: [MyMixin1,MyMixin2],componentDidMount: function() { // 调用 mixin1 共享的方法 this.someMethod(); } }); 更多 mixins 的使用会在第三章中讲解。 1.4.3 statics类型: statics 可以定义组件的类方法 eg: var MyComponent = React.createClass({ statics: { customMethod: function(foo) { return foo === 'bar'; } } }); MyComponent.customMethod('bar'); // true React 的组件是 OOP 的思维,MyComponent 是一个 class,class 分为类方法和实例方法,实例方法可以访问 this,然而类方法不能,所以我们不能在 Class 中返回状态或者属性。 1.4.4 displayName类型: 为了显示调试信息,每个组件都会有一个名称,JSX 在转为 JS 的时候自动的设置 displayName,如下: // Input (JSX): var MyComponent = React.createClass({ }); // Output (JS): var MyComponent = React.createClass({displayName: "MyComponent",}); 当然我们也可以自定义 displayName 1.4.5 生命周期方法下图描述了整个组件的生命周期,包含的主要几种情况:
1.4.6 componentWillMountvoid componentWillMount() 条件:第一次渲染阶段在调用 render 方法前会被调用 1.4.7 componentDidMountvoid componentDidMount() 条件:第一次渲染成功过后,组件对应的 DOM 已经添加到页面后调用 1.4.8 componentWillReceiveProps(newProps)void componentWillReceiveProps( object nextProps ) 条件: 当组件获取新属性的时候,第一次渲染不会调用 componentWillReceiveProps: function(nextProps) { this.setState({ likesIncreasing: nextProps.likeCount > this.props.likeCount }); } 注意: 这个时候虽说是获取新属性,但并不能确定属性一定改变了,例如一个组件被多次渲染到 DOM 中,如下面: var Component = React.createClass({ componentWillReceiveProps: function(nextProps) { console.log('componentWillReceiveProps',nextProps.data.bar); },rener: function() { return <div> {this.props.data.bar} </div> } }); var container = document.getElementById('container'); var mydata = {bar: 'drinks'}; ReactDOM.render(<Component data={mydata} />,container); ReactDOM.render(<Component data={mydata} />,container); 结果会输出两次 componentWillReceiveProps,虽然属性数据没有改变,但是仍然会调用 componentWillReceiveProps 方法。
1.4.9 shouldComponentUpdate(nextProps,nextState)boolean shouldComponentUpdate( object nextProps,object nextState ) 条件: 接收到新属性或者新状态的时候在 render 前会被调用(除了调用 forceUpdate 和初始化渲染以外) 1.4.10 componentWillUpdatevoid componentWillUpdate( object nextProps,object nextState ) 条件:当组件确定要更新,在 render 之前调用 1.4.11 componentDidUpdatevoid componentDidUpdate( object prevProps,object prevState ) 条件:更新被应用到 DOM 之后 1.4.12 生命周期与单向数据流我们知道 React 的核心模式是单向数据流,这不仅仅是对于组件级别的模式,在组件内部 的生命周期中也是应该符合单向数据的模式。数据从组件的属性流入,再结合组件的状态,流入生命周期方法,直到渲染结束这都应该是一个单向的过程,其间不能随意改变组件的状态。
1.4.13 实例练习:通过 mixin 打印出组件生命周期的执行顺序@todo (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |