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

1. 問題描述

當我新克隆一個react項目,而後安裝好依賴包後,啓動服務,發現瀏覽器控制檯報以下warning:node

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

QQ20191101-004128.png

2. 問題緣由

從報錯的信息大體能夠知道,react部分舊的生命週期(### componentWillMount)在新的版本中(react 17.0以上版本)將會棄用,須要更名字(UNSAFE_componentWillMount)。react

因爲在代碼項目中沒有使用componentWillMount生命週期,而且如今react版本尚未出到17.0(2019-11-01),爲了避免報這個Warning,須要解決此問題。npm

2.1 項目中的react版本

通過查看我項目中package.json文件中,react的版本:json

"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的版本:dom

"dependencies": {
    "react": "16.4.1",
    "react-dom": "16.4.1",
  }

而後刪除項目中node_modules文件夾,從新安裝依賴包便可,ide

若是發現仍是報warning,那麼,請刪除package-lock.json文件,在刪除node_modules文件夾,從新安裝依賴包。
而後運行項目就沒有warning了。測試

相關文章
相關標籤/搜索