React.js挂载阶段的组件生命周期

组件的挂载指的是将组件渲染并且构造 DOM 元素然后插入页面的过程。这是一个从无到有的过程,React.js 提供一些生命周期函数可以给我们在这个过程中做一些操作。

React.js 将组件渲染,并且构造 DOM 元素然后塞入页面的过程称为组件的挂载。这一节我们学习了 React.js 控制组件在页面上挂载和删除过程里面几个方法:

  • componentWillMount:组件挂载开始之前,也就是在组件调用 render 方法之前调用。
  • componentDidMount:组件挂载完成以后,也就是 DOM 元素已经插入页面后调用。
  • componentWillUnmount:组件对应的 DOM 元素从页面中删除之前调用。

总结
我们一般会把组件的 state 的初始化工作放在 constructor 里面去做;
在 componentWillMount 进行组件的启动工作,例如 Ajax 数据拉取、定时器的启动;
组件从页面上销毁的时候,有时候需要一些数据的清理,例如定时器的清理,就会放在 componentWillUnmount 里面去做。
例子
完成 Post 组件,它可以加载、刷新文章内容。

已有函数 getPostData,它会返回一个 Promise,你可以通过它获取文章的内容。

getPostData().then((postContent) => {
  // ...
})

在获取数据的时候,Post 组件的 div.post-content 中显示 数据加载中…,完成加载以后直接显示 getPostData 的返回结果。

页面有个按钮,点击可以重新加载数据。

class Post extends Component {
  constructor(){
    super();
    this.state={
      content:''
    }
  }
  componentWillMount(){
    this.setState({content:'数据加载中...'});
  }
  handleClick(){
    this.setState({content:'数据加载中...'});
    getPostData().then((postContent) => {
      this.setState({content:postContent});
    })
  }
  componentDidMount(){
     getPostData().then((postContent) => {
      this.setState({content:postContent});
    })
  }
  render () {
    return (
      <div>
        <div className='post-content'>{this.state.content}</div>
        <button onClick={this.handleClick.bind(this)}>刷新</button>
      </div>
    )
  }
}

以上是局部代码片段。

猜你喜欢

转载自blog.csdn.net/homer_simpson/article/details/80656555