You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React父组件状态更新后子组件未同步刷新的原因是什么?

问题原因

  • 你的NumberInput子组件内部单独维护了一个value状态,这个状态的初始值仅在组件第一次渲染时从props的item获取,后续父组件传入的item更新时,子组件内部的value状态不会自动同步最新的props值,所以就出现了值不更新的情况。
  • 而原生的input没有单独维护内部状态,直接绑定的是父组件传入的item.name,所以父组件状态更新时会同步刷新。

解决方案

方案1:删除子组件内部冗余状态(推荐)

子组件不需要自己维护value状态,直接绑定父组件传入的item对应属性即可,避免双向状态不同步:

export const NumberInput: FC<NumberInputProps> = ({
  item,
  setter,
  ...rest
}) => {
  const assignValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    const inputValue = e.currentTarget.value;
    if (!isNaN(parseFloat(inputValue))) {
      const temp = { ...item };
      temp[rest.name as string] = parseFloat(inputValue);
      setter(temp);
    }
  };

  return <input value={item[rest.name as string]} onChange={assignValue} {...rest} />;
};

方案2:监听props变化同步更新内部状态

如果确实需要在子组件内部维护状态,可以添加useEffect监听item的变化,同步更新内部的value:

export const NumberInput: FC<NumberInputProps> = ({
  item,
  setter,
  ...rest
}) => {
  const [value, setValue] = useState(item[rest.name as string].toString());

  // 新增useEffect监听item变化,同步更新内部状态
  useEffect(() => {
    setValue(item[rest.name as string].toString());
  }, [item, rest.name]);

  const assignValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    const inputValue = e.currentTarget.value;
    if (!isNaN(parseFloat(inputValue))) {
      const temp = { ...item };
      temp[rest.name as string] = parseFloat(inputValue);
      setter(temp);
    }
    setValue(inputValue);
  };

  return <input value={value} onChange={assignValue} {...rest} />;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:24:04