警告: componentWillMount 有是 renamed
错误信息
componentWillMount 有是 renamed, and 是不 recommended for use.
快速摘要
你 used deprecated unsafe lifecycle 方法 (componentWillMount, componentWillReceiveProps, componentWillUpdate).
为什么发生
Used
componentWillMountin 类组件Used
componentWillReceivePropsorcomponentWillUpdate复制从 旧 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
componentWillin codebaseIdentify 什么方法是 做 (设置, 更新, etc.)
如何修复
Replace
componentWillMount使用componentDidMountor useEffectReplace
componentWillReceiveProps使用getDerivedStateFromPropsor useEffectReplace
componentWillUpdate使用componentDidUpdateor useEffect
如何预防
Use 函数组件使用 Hook 相反的 类组件
从不 use
componentWill*lifecycle 方法
相关资源
相关课程
- 组件 Lifecycle
学习 modern lifecycle 模式.