用途
react18-lifecycle-patterns 是一份迁移参考,用于把三个不安全的类组件生命周期方法改写为符合 React 18.3.1 的规范写法。涉及的方法为:componentWillMount、componentWillReceiveProps、componentWillUpdate。
主要能力
该技能提供「迁移前/迁移后」的精确对照模式,并以决策指南的方式引导选择正确的迁移目标。指南按生命周期方法实际承担的语义分类:
- componentWillMount:若用于设置初始 state(this.setState(...)),迁移到 constructor;若用于运行副作用(fetch、订阅、DOM),迁移到 componentDidMount;若用于从 props 派生初始 state,迁移到带 props 的 constructor。
- componentWillReceiveProps:若为 props 变化触发的异步副作用(fetch、取消),迁移到 componentDidUpdate;若为从新 props 纯派生 state(无副作用),迁移到 getDerivedStateFromProps。
- componentWillUpdate:若在更新前读取 DOM(滚动、尺寸、位置),迁移到 getSnapshotBeforeUpdate;若在更新前取消请求/运行副作用,迁移到 componentDidUpdate 并配合 prev 比较。
UNSAFE_ 前缀规则
技能明确指出:不要将 UNSAFE_componentWillMount、UNSAFE_componentWillReceiveProps、UNSAFE_componentWillUpdate 作为永久修复方案。加前缀虽然能压制 React 18.3.1 的警告,但并不会:修复并发模式安全问题;为 React 19 做准备(React 19 中这些方法无论是否带前缀都会被移除);修复迁移本应解决的底层语义问题。UNSAFE_ 前缀只适合作为安排正式迁移前的临时保留,并建议加上注释标记,例如:
// TODO: React 19 will remove this. Migrate before React 19 upgrade. // UNSAFE_ prefix added temporarily - replace with componentDidMount / getDerivedStateFromProps / etc.
使用方式
这是一份参考文档类技能,使用方式是:在编写任何迁移代码前,先阅读与所迁移生命周期方法对应的参考文件。参考文件包括:
- references/componentWillMount.md —— 3 种情形,含完整的前后代码
- references/componentWillReceiveProps.md —— getDerivedStateFromProps 陷阱警告与完整示例
- references/componentWillUpdate.md —— getSnapshotBeforeUpdate 与 componentDidUpdate 的配对使用
适用场景
适用于正在将既有 React 类组件代码库升级到 React 18.3.1、并需要处理上述三个不安全的生命周期方法的开发者。
限制
资料未提供安装命令、价格、平台与效果数据等信息,暂未提供。