- 問題描述
當我新克隆一個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
- 問題原因
從報錯的信息大致可以知道,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了。
作者:dragon
鏈接:https://segmentfault.com/a/1190000020875617
來源:SegmentFault 思否
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。