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()});
          }
        );
      }
    }

发布了31 篇原创文章 · 获赞 13 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_42881744/article/details/105706084
今日推荐