Skip to content

警告: componentWillMount 有是 renamed

错误信息

                componentWillMount 有是 renamed, and 是不 recommended for use.
              

快速摘要

你 used deprecated unsafe lifecycle 方法 (componentWillMount, componentWillReceiveProps, componentWillUpdate).

为什么发生

  • Used componentWillMount in 类组件

  • Used componentWillReceiveProps or componentWillUpdate

  • 复制从 旧 React 教程 or codebases

最小示例

✗ 错误代码
class MyComponent extends React.Component {
  componentWillMount() {
    fetchData(); // Deprecated!
  }
}
✓ 修复代码
function MyComponent() {
  useEffect(() => {
    fetchData();
  }, []);
  return <div />;
}

useEffect 使用空 deps replaces componentWillMount. 它运行之后 mount, 哪个是 safe and 正确 timing.

如何诊断

  • 搜索 for componentWill in codebase

  • Identify 什么方法是 做 (设置, 更新, etc.)

如何修复

  • Replace componentWillMount 使用 componentDidMount or useEffect

  • Replace componentWillReceiveProps 使用 getDerivedStateFromProps or useEffect

  • Replace componentWillUpdate 使用 componentDidUpdate or useEffect

如何预防

  • Use 函数组件使用 Hook 相反的 类组件

  • 从不 use componentWill* lifecycle 方法

相关资源

相关术语

相关课程

← 返回语言