在我的代码中,我没有任何显式使用 componentWillMount
,但在运行 webpack
时我仍然看到一些警告.
react-dom.development.js:12386 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: foo, bar
我确实运行了建议的npx react-codemod rename-unsafe-lifecycles
,但警告并没有消失,只是将其措辞更改为
react-dom.development.js:12386 Warning: componentWillMount has been renamed, and is not recommended for use. [...]
这里,foo
和bar
都是我们团队编写的自定义组件,以及一些外部库的组件。对 Visual Studio 解决方案的 componentWillMount
的完整搜索没有给我任何结果。有人可以向我解释一下我可能做错了什么吗?
我在 another question 阅读一条评论指出
I don't have any explicit place with
componentWillMount
, but I do have [...] a line of code after the constructor withstate={ tabindex:0 }
How do I "move" that into the constructor?
答案是写
构造函数(props) {super(props); this.state = { tabindex:0 }}
。有人可以解释一下这里发生了什么事吗?我必须在代码中寻找什么样的模式?
更多详细信息
printWarning @ react-dom.development.js:12386
lowPriorityWarningWithoutStack @ react-dom.development.js:12407
./node_modules/react-dom/cjs/react-dom.development.js.ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings @ react-dom.development.js:12577
flushRenderPhaseStrictModeWarningsInDEV @ react-dom.development.js:25641
commitRootImpl @ react-dom.development.js:24871
unstable_runWithPriority @ scheduler.development.js:815
runWithPriority$2 @ react-dom.development.js:12188
commitRoot @ react-dom.development.js:24865
finishSyncRender @ react-dom.development.js:24251
performSyncWorkOnRoot @ react-dom.development.js:24223
scheduleUpdateOnFiber @ react-dom.development.js:23590
scheduleRootUpdate @ react-dom.development.js:26945
updateContainerAtExpirationTime @ react-dom.development.js:26973
updateContainer @ react-dom.development.js:27075
(anonymous) @ react-dom.development.js:27663
unbatchedUpdates @ react-dom.development.js:24375
legacyRenderSubtreeIntoContainer @ react-dom.development.js:27662
render @ react-dom.development.js:27756
./src/index.tsx @ index.tsx:52
__webpack_require__ @ bootstrap:19
0 @ bundle.js:152632
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83
相关
最佳答案
您收到此警告是因为 componentWillMount
在较新的 React 版本中已弃用。如果您不使用componentWillMount
无论您的库之一在哪里,它都需要更新。
如果这让您感觉好一些,您的生产版本将不会在控制台中显示这些警告。
如果您由于某种原因无法更新库,您可以尝试在控制台中输入类似 console.warn = () => {}
的内容来抑制这些错误。在您的App
的顶部组件,但我不会推荐这个,因为那样你将无法使用 console.warn
稍后在您的代码中。在您能够更新您的库之前,最好将它们视为一种烦恼。
关于javascript - 即使未显式使用 `componentWillMount`,'componentWillMount' 警告仍可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58769752/