【问题标题】:React useState overwrites state object instead of merging [duplicate]React useState 覆盖状态对象而不是合并 [重复]
【发布时间】:2021-03-16 01:38:16
【问题描述】:

React 没有合并我对状态对象所做的更改,而是完全覆盖它。

这可能是由上下文引起的吗?我不确定是否可以直接将调度事件作为道具传递。我尝试将 setParams 包装在另一个函数中,例如在 "lifting state up" docs 中,但是没有效果。

预期输出

{width: 400, height: 400, strokeWeight: 0.25, color: "#d9eb37", resolution: 10}

电流输出

{color: "#d9eb37"}

React 上下文保存状态

const Context = createContext();

const Provider = ({ children }) => {
  const [params, setParams] = useState({
    width: 400,
    height: 400,
    strokeWeight: 0.25,
    color: "#ad3e00",
    resolution: 10
  });

  return (
    <Context.Provider value={{ params, setParams }}>
      {children}
    </Context.Provider>
  );
};

通用输入组件

const Input = () => {
  const { params, setParams } = useContext(Context);

  render(
    <input
        type="color"
        value={params.color}
        onChange={(e) => setParams({ color: e.target.value })}
      />
  );
}

【问题讨论】:

  • useState 就是这样工作的。它替换了值,它不进行任何合并。那是你的事
  • 我建议使用 setParamsfunctional update form 来设置状态(仅在 cmets 和上述链接问题的未接受答案中提及)。

标签: reactjs


【解决方案1】:

useState 不会像 setState 那样在类组件中合并状态,您必须自己完成这项工作。

onChange={(e) =&gt; setParams((params)=&gt;({ ...params, color: e.target.value }))}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-22
    • 2020-04-21
    • 2021-07-04
    • 2011-11-24
    • 2017-11-27
    • 2014-01-02
    • 1970-01-01
    • 2020-11-29
    相关资源
    最近更新 更多