react:Warning:componentWillMount has been renamedの問題の解決

1774 ワード

1.問題の説明
reactプロジェクトを新しくクローンし、依存パッケージをインストールした後、サービスを開始すると、ブラウザコンソールに次のwarningが表示されます.
VM25 common.bundle.js:36926 Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

Please update the following components: Router, RouterContext

2.問題の原因
エラーを報告した情報から、react部分の古いライフサイクル(###componentWillMount)は新しいバージョン(react 17.0以上のバージョン)で廃棄され、名前を変更する必要があることがわかります(UNSAFE_componentWillMount).
コードプロジェクトでcomponentWillMountライフサイクルが使用されておらず、reactバージョンはまだ17.0(2019-11-01)に出ていないため、このWarningを報告しないために、この問題を解決する必要があります.
2.1プロジェクトのreactバージョン
私のプロジェクトのpackageを確認しました.jsonファイル、reactのバージョン:
"dependencies": {
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
  }
npm installコマンドを使用してインストールした後、インストールされたreactバージョンは16.11.0で、このプロジェクトを実行するとWarningに報告されます.テストの結果、reactバージョンが16.4.1にインストールされた後、実行項目はこのWarningを報告しません.
2.2解決方法
プロジェクトのpackageを変更します.jsonファイル、reactのバージョン:
"dependencies": {
    "react": "16.4.1",
    "react-dom": "16.4.1",
  }

次に、プロジェクトのnode_を削除します.modulesフォルダ、依存パッケージを再インストールすれば、
warningが検出された場合は、package-lock.jsonファイルを削除し、node_を削除します.modulesフォルダ、依存パッケージを再インストールします.そしてプロジェクトを実行するとwarningはありません.