react-native - 将 componentWillReceiveProps 重命名为 componentDidUpdate
问题描述
我正在按照本教程构建可扩展的列表视图:
https://medium.com/@iakash1195/expandable-listview-in-react-native-53ebdd78abea
它有效,但我收到一条警告说:
警告:componentWillReceiveProps 已重命名,不推荐使用。有关详细信息,请参阅 fb.me/react-unsafe-component-lifecycles。
- 将数据获取代码或副作用移动到 componentDidUpdate。
- 如果您在 props 更改时更新状态,请重构您的代码以使用记忆技术或将其移动到静态 getDerivedStateFromProps。了解更多信息:
- 将 componentWillReceiveProps 重命名为 UNSAFE_componentWillReceiveProps 以在非严格模式下抑制此警告。在 React 17.x 中,只有 UNSAFE_ 名称可以使用。要将所有已弃用的生命周期重命名为新名称,您可以
npx react-codemod rename-unsafe-lifecycles
在项目源文件夹中运行。
我试图将 componentWillReceiveProps 重命名为 componentDidUpdate,但可扩展列表视图停止工作
我可以只运行命令来重命名已弃用的函数,但这个解决方案远非最好的。
npx react-codemod rename-unsafe-lifecycles --force
解决方案
正如警告所暗示的,componentWillReceiveProps
已弃用,您应该static getDerivedStateFromProps
改用。
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.item.isExpanded && prevState.layoutHeight)
return {
layoutHeight: null
};
return {
layoutHeight: 0
};
}
您可以在getDerivedStateFromProps阅读有关此生命周期方法的更多信息