Warning: componentWillMount has been renamed, and is not recommended for use

The Problem

Warning: componentWillMount has been renamed, and is not recommended
for use

  1. Initializing state 初始化状态

// Before

class AppComponent extends React.Component {
  state = {};

  componentWillMount() {
    this.setState({
      selected: this.props.selected,
      color: "red"
    });
  }
}
  1. Fetching external data 提取外部数据

// Before

class AppComponent extends React.Component {
  state = {
    data: null,
  };

  componentWillMount() {
    fetch("https://sentry.io/data").then(
      res => {
        this.setState({data: res.json()});
      }
    );
  }
}

The Solution

从React版本16.3开始,以下组件生命周期方法正在逐步淘汰。

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

如果要使用这些方法,请在方法前面加上UNSAFE_。 这些方法被认为是“不安全的”,因为React团队期望依赖于这些方法的代码更有可能在React的未来版本中出现错误。

根据代码的目标,您可以完全将componentWillMount与其他生命周期方法一起使用。

解决方案是将状态初始化移至构造函数或属性初始化器,如下所示:

// After
class AppComponent extends React.Component {
  state = {
		selected: this.props.selected,
    color: "red"
  };
}

解决方案是将数据获取移到componentDidMount中:

 // After
    class AppComponent extends React.Component {
      state = {
        data: null,
      };

      componentDidMount() {
        fetch("https://sentry.io/data").then(
          res => {
            this.setState({data: res.json()});
          }
        );
      }
    }

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值