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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章