在 React 16.x 的类组件中,当组件接收新的 props 时,应优先在哪个生命周期方法中根据 props 更新响应?请说明该场景下此方法的作用与执行时机。
考察说明
考察对 React 16.x 类组件生命周期中 props 更新阶段方法的理解。
回答思路
- 【回答框架 1】在 React 16.x 类组件中,props 变化导致的更新阶段,通常使用 componentWillReceiveProps 或 getDerivedStateFromProps 来处理。旧版常用 componentWillReceiveProps,但 React 16.3 起已标记为不安全,推荐使用静态方法 getDerivedStateFromProps。
- 【回答框架 2】getDerivedStateFromProps 在组件实例化后和接收新 props 时在 render 之前调用,它接收 props 和 state,返回一个对象来更新 state,或返回 null 表示不需要更新。此方法应保持纯净,不应执行副作用。
- 【回答框架 3】若仅需在 props 变化后执行副作用(如请求数据),可配合 componentDidUpdate 使用,在其中比较 prevProps 和 this.props 来确定是否发生变化,避免不必要的重复请求。
- 【回答框架 4】生命周期顺序:getDerivedStateFromProps -> render -> componentDidUpdate,因此若需基于新 props 重置内部状态,应在 getDerivedStateFromProps 中计算新 state,而副作用操作放在 componentDidUpdate 中比较前后 props 后执行。
- 【关键点 1】React 16.x 中处理 props 更新的推荐方法是 getDerivedStateFromProps。
- 【关键点 2】componentWillReceiveProps 在 16.3 后不再推荐使用。
- 【关键点 3】getDerivedStateFromProps 是静态方法,不适合执行副作用。
- 【关键点 4】副作用应放在 componentDidUpdate 中,通过比较 prevProps 与 this.props 实现。
- 【易错点 1】不建议在 getDerivedStateFromProps 内执行异步请求或修改外部变量,它应为纯函数。
- 【易错点 2】不能误以为 getDerivedStateFromProps 只在 props 变化时调用,它在初始化时也会被调用,需注意初始逻辑。
- 【易错点 3】若使用 componentWillReceiveProps 忽略其废弃标识,可能导致未来升级警告和潜在问题,建议迁移。