状态
组件的生命周期可分成三个状态:
Mounting:已插入真实 DOM
Updating:正在被重新渲染
Unmounting:已移出真实 DOM
方法
生命周期的API有:getDefaultProps
作用于组件类,只调用一次,返回对象用于设置默认的props,对于引用值,会在实例中共享。getInitialState
作用于组件的实例,在实例创建时调用一次,用于初始化每个实例的state,此时可以访问this.props。render
必选的方法,创建虚拟DOM,该方法具有特殊的规则:
componentWillMount
在渲染前调用,在客户端也在服务端。componentDidMount
: 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout,setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI)。componentWillReceiveProps
在组件接收到一个新的prop时被调用。这个方法在初始化render时不会被调用。shouldComponentUpdate
返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。componentWillUpdate
在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。componentDidUpdate
在组件完成更新后立即调用。在初始化时不会被调用。componentWillUnmount
在组件从 DOM 中移除的时候立刻被调用。
实例化
当组件在客户端被实例化,第一次被创建时,以下方法依次被调用:
getDefaultProps
getInitialState
componentWillMount
render
componentDidMount
getDefaultProps
getInitialState
componentWillMount
render
componentDidMount 不会在服务端被渲染的过程中调用。
存在期
此时组件已经渲染好并且用户可以与它进行交互,比如鼠标点击,手指点按,或者其它的一些事件,导致应用状态的改变,你将会看到下面的方法依次被调用
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate
示例
- import React from 'react';
- import ReactDOM from 'react-dom';
- class Button extends React.Component {
- constructor(props) {
- super(props);
- console.log('init');
- this.state = {
- data : 0
- }
- }
- setNewNumber = () => {
- this.setState({
- data : this.state.data + 1
- })
- }
- render() {
- return (
- <div>
- <button onClick = {this.setNewNumber}>insert</button>,<Content myNumber = {this.state.data}/>
- </div>
- )
- }
- }
- class Content extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- opacity: props.opacity || 1
- }
- }
- componentWillMount() {
- console.log('Component WILL MOUNT!')
- }
- componentDidMount() {
- console.log('Component DID MOUNT!')
- }
- componentWillReceiveProps = (newProps) => {
- console.log('Component WILL RECIEVE PROPS!')
- }
- shouldComponentUpdate = (newProps,newState) => {
- return true;
- }
- componentWillUpdate = (nextProps,nextState) => {
- console.log('Component WILL UPDATE!');
- }
- componentDidUpdate = (prevProps,prevState) => {
- console.log('Component DID UPDATE!')
- }
- componentWillUnmount() {
- console.log('Component WILL UNMOUNT!')
- }
- render() {
- return (
- <div>
- <h1>{this.props.myNumber}</h1>
- </div>
- )
- }
- }
- ReactDOM.render(
- <Button/>,document.getElementById('lifetime')
- );
初始化:
状态变化: