即使未明确使用“componentWillMount”,也会显示“componentWillMount”警告

新手上路,请多包涵

在我的代码中, 我没有明确使用 componentWillMount ,但在运行 webpack 时我仍然看到一些警告。

react-dom.development.js:12386 警告:componentWillMount 已重命名,不建议使用。有关详细信息,请参阅 https://fb.me/react-unsafe-component-lifecycles。

  • 将有副作用的代码移至 componentDidMount,并在构造函数中设置初始状态。
  • 将 componentWillMount 重命名为 UNSAFE_componentWillMount 以在非严格模式下抑制此警告。在 React 17.x 中,只有 UNSAFE_ 名称有效。要将所有已弃用的生命周期重命名为新名称,您可以在项目源文件夹中运行 npx react-codemod rename-unsafe-lifecycles

请更新以下组件:foo、bar

我确实运行了建议的 npx react-codemod rename-unsafe-lifecycles ,但警告并没有消失,只是将其措辞改为

react-dom.development.js:12386 警告:componentWillMount 已重命名,不建议使用。 […]

这里, foobar 都是我们团队编写的自定义组件,以及一些外部库的组件。全面搜索 componentWillMount 的 Visual Studio 解决方案没有给我任何结果。有人可以向我解释我做错了什么吗?

我在 另一个问题 上读到一条评论说

我没有任何明确的地方 componentWillMount ,但我在构造函数之后有 […] 一行代码 state={ tabindex:0 } 构造函数?

答案是写 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

有关的

原文由 B–rian 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 616
2 个回答

您收到此警告是因为 componentWillMount 在较新的 React 版本中已弃用。如果您没有在任何地方使用 componentWillMount ,那么您的库之一就需要更新。

如果它让您感觉更好,您的生产构建将不会在控制台中显示这些警告。

如果您出于任何原因无法更新库,您可以尝试通过在控制台中放置类似 console.warn = () => {} 的内容来抑制这些错误 App 组件的顶部,但我不推荐从那时起,您将无法在稍后的代码中使用 console.warn 。在您能够更新您的图书馆之前,最好只是接受它们作为一种烦恼。

原文由 Matt Croak 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您想将所有已弃用的生命周期(如 componentWillMount 或 componentWillReceiveProps)重命名为新名称,您可以在项目源文件夹中运行 npx react-codemod rename-unsafe-lifecycles

原文由 Samiul Lesum 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题