【发布时间】: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就是这样工作的。它替换了值,它不进行任何合并。那是你的事 -
我建议使用
setParams的 functional update form 来设置状态(仅在 cmets 和上述链接问题的未接受答案中提及)。
标签: reactjs