首页 > 解决方案 > React useState 覆盖状态对象而不是合并

问题描述

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

这可能是由上下文引起的吗?我不确定是否可以直接将调度事件作为道具传递。我试过包装setParams另一个功能,比如在“提升状态”文档中,但是没有效果。

预期产出

{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 })}
      />
  );
}

标签: reactjs

解决方案


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

onChange={(e) => setParams((params)=>({ ...params, color: e.target.value }))}


推荐阅读