React17.0生命周期调整

React17.0生命周期调整

在即将到来的react17.0版本,react团队对生命周期做了调整,将会移除 componentWillMount,componentWillReceiveProps,componentWillUpdate这三个生命周期,因为这些生命周期方法容易被误解和滥用。

组件数据初始化

一般我们为了提前 setState ,防止二次渲染(第一次是空state渲染,第二次外部数据渲染),经常在 componentWillMount 生命周期请求数据

// Before
class ExampleComponent extends React.Component {
   
  state = {
   
    externalData: null,
  };

  componentWillMount() {
   
    this._asyncRequest = asyncLoadData().then(
      externalData => {
   
        this._asyncRequest = null;
        this.setState({
   externalData});
      }
    );
  }

  componentWillUnmount() {
   
    if (this._asyncRequest) {
   
      this._asyncRequest.cancel();
    }
  }

  render() {
   
    if (this.state.externalData === null) {
   
      // Render loading state ...
    } else {
   
      // Render real UI ...
    }
  }
}

但是事实却不是这样的,异步获取外部数据不一定会在渲染之前返回,这也意味着组件也有可能会被渲染一次,为了后面新版本实现异步渲染,建议请求放在 componentDidMount 来调用。
还有一个问题是,componentWillMount 在服务端渲染(nuxt.js)的时候会导致服务端和客户端各渲染一次,而 componentDidMount 只在客户端渲染一次

// After
class ExampleComponent extends React.Component {
   
  state = {
   
    externalData: null,
  };

  componentDidMount() {
   
    this._asyncRequest = loadMyAsyncData().then(
      externalData => {
   
        this._asyncRequest = null;
        this.setState({
   externalData});
      }
    );
  }

  componentWillUnmount() {
   
    if (this._asyncRequest) {
   
      this._asyncRequest.cancel();
    }
  }

  render() {
   
    if (this.state.externalData === null) {
   
      
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值