[英]Easier way to set React or Recoil state objects with array properties
希望有人可以帮助我以更简单的方式更新我在更复杂的对象/数组上的反冲状态。 我主要是 C# 开发人员,但试图学习一些体面的编码 javascript 的方法。 这看起来很丑陋而且过于复杂,就像我的代码目前的样子。
由于 state 实例是只读的,我无法直接更改它的值。 使用下划线克隆方法甚至不会改变这一点。
所以这是我的简化对象,在现实生活中有很多不相关的属性:
interface IDeviceAttributeValue {
/** The unique value key
id: string;
/** The attribute value */
value: any;
}
interface IDeviceAttribute {
/** A unique key to identify the attribute. Normally the OSC address of the setting is used */
key: string;
/** The list of attribute values */
values: IDeviceAttributeValue[];
}
在 React 我有 state 声明const [attribute, setAttribute] = useState(props.attribute as IDeviceAttribute);
或者其他一些地方 Recoil state: const [deviceAttributeState, setDeviceAttributeState] = useRecoilState(recoilDeviceAttributeState);
在代码的某处,我需要更改值数组上的值并更新 state。 在 React state 和 Recoil state 的两种情况下,“getter”实例都是只读/常量。
我最终得到了这个:
... code calculating a new value for existing value in editedSetting: IDeviceAttributeValue
...
// Now update state, first find the element in the array
let index = attribute.values.findIndex(l => l.id === editedSetting.id);
if (index !== -1) {
let newValueItem = {
...attribute.values[index],
value: newValue
}
setAttribute({
...attribute,
values: [...attribute.values.slice(0,index - 1), newValueItem,
...attribute.values.slice(index + 1)]
})
}
这么多行代码用于简单的 state 更新:我敢肯定,对于某人来说,这是非常微不足道的任务,可以做得更优雅:-)
感谢您的帮助和时间
如果这在您的代码中很常见,那么您可以将更新逻辑提取到自定义挂钩中。 我在想类似的东西
function useDeviceAttribute(initialValue: IDeviceAttribute) {
const [attribute, setAttribute] = useState(initialValue);
const updateAtId = (id: number, newValue: any) => {
let index = attribute.values.findIndex(l => l.id === id);
if (index !== -1) {
let newValueItem = {
...attribute.values[index],
value: newValue
}
setAttribute({
...attribute,
values: [...attribute.values.slice(0,index - 1), newValueItem,
...attribute.values.slice(index + 1)]
})
}
};
return [attribute, updateAtId];
}
所以你的组件代码会是这样的
function YourComponent(props) {
const [attribute, updateAtId] = useDeviceAttribute(props.attribute);
//
// your component code goes here
//
// ... code calculating a new value for existing value in editedSetting: IDeviceAttributeValue
/// ...
// Now update state, first find the element in the array
updateAtId(editedSetting.id, newValue);
}
好的,似乎没有办法更新基于对象/数组的状态而不使用扩展运算符并处理深度更新,因为浅层属性更新仅适用于顶层。
这意味着您必须注意提供当前 state 中的现有属性值,并设置要并行更改的属性值,您需要在每个嵌套级别上执行此操作。
我在这里找到了一个很好的 q/a 提供示例: 博客
因此,在我的情况下,我最终得到了这样的代码,用于更新具有数组属性(设置)的 object,其中数组中的一个特定元素具有新值:
setEditedDeviceState(curVal => ({
...curVal,
settings: curVal.settings.map(
el => el.key === attribute.key ? attribute : el
)
}));
我必须管理,我发现这是一个痛苦的......并且候选人很容易在你的数据模型中引入错误。 如果这是语言本身的缺陷或反应的实现(反冲,redux 或其他)状态可能可以进一步讨论。 但似乎这是你目前必须忍受的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.