reactjs - 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 })}
/>
);
}
解决方案
useState
不像setState
在类组件中那样合并状态,您必须自己完成这项工作。
onChange={(e) => setParams((params)=>({ ...params, color: e.target.value }))}
推荐阅读
- javascript - 如何按每个数组项中具有不同名称的单个属性进行排序?
- javascript - 无法通过动态导入访问对象属性。Vue.js + ts
- jboss - 无论部署扫描器中设置的默认超时如何,JBoss AS 7.1 服务器在启动过程中都无法部署 ear 应用程序
- python - 使用 R 数据表的 .SDcols 样式的 pydatatable 更新或添加多列
- javascript - 使用带有选项元素的表单生成自定义 iframe
- pytorch - Pytorch:解释 torch.argmax
- laravel - 为什么不更新数据库并返回此错误?
- javascript - 动态创建时隐藏的输入字段,对于临时存储字符串没有多大用处
- python - Python Idle 编辑中的代码不会在 shell 中运行
- reactjs - useEffect 在分页更改时使 axios 调用两次(?)