解决react: Warning:componentWillMount has been renamed 问题

  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

  1. 问题原因

    从报错的信息大致可以知道,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 思否

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。