You need to enable JavaScript to run this app. 如何在状态更新场景下让getDerivedStateFromProps替代UNSAFE_componentWillReceiveProps
优惠活动
大模型
产品
解决方案
定价
更多

如何在状态更新场景下让getDerivedStateFromProps替代UNSAFE_componentWillReceiveProps

问题根因

UNSAFE_componentWillReceiveProps 仅在父组件重渲染触发props更新时才会执行,子组件自身调用setState不会触发该生命周期。但getDerivedStateFromProps会在组件每次渲染(包括自身state更新触发的渲染)时都执行,因此你在onChange中修改parameters后,该钩子会立即执行,用旧的props值覆盖你刚更新的state。

解决方案

官方推荐的解法是在state中新增一个字段,缓存上一次用于更新state的props关联值,只有当props对应值真的发生变化时,才用props更新state,否则跳过更新。

步骤1:扩展state类型

给ICustomActionModalState新增字段prevActionStatement,用于缓存上一次props传入的actionToEdit.statement值:

interface ICustomActionModalState {
  // 原有其他state字段
  parameters: RegExpMatchArray | null;
  prevActionStatement?: string;
}

步骤2:初始化state

在constructor中给新增字段赋初始值:

constructor(props: ICustomActionModalProps) {
  super(props);
  const initStatement = props.actionToEdit?.statement;
  this.state = {
    // 原有其他state字段初始值
    parameters: initStatement?.match(/@\w+/g) || null,
    prevActionStatement: initStatement
  };
}

步骤3:修改getDerivedStateFromProps逻辑

增加props和缓存值的比对逻辑,只有值变化时才更新state:

static getDerivedStateFromProps(
    nextProps: ICustomActionModalProps, 
    prevState: ICustomActionModalState
) {
    const currentStatement = nextProps?.actionToEdit?.statement;
    // 只有props中的statement存在,且和上一次缓存的值不一致时,才更新state
    if (currentStatement && currentStatement !== prevState.prevActionStatement) {
        const regex = /@\w+/g;
        const found = currentStatement.match(regex);
        return {
            parameters: found,
            prevActionStatement: currentStatement
        };
    }
    // 无变化则返回null,不修改state
    return null; 
}

修改后getDerivedStateFromProps的表现会和原UNSAFE_componentWillReceiveProps完全一致:仅当父组件传入的actionToEdit.statement真的发生变化时,才用props值更新parameters,子组件内部onChange修改的parameters不会被旧props覆盖。

内容的提问来源于stack exchange,提问作者ffcabbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 13:36:04