我正在为我的React 16.13.0应用程序使用React钩子。我正在尝试编写一个通用函数来更新状态下的复杂对象的属性。
const [coop, setCoop] = React.useState(props.coop);
我的表单包含如下元素
<Input
inputType={"text"}
title={"Name"}
name={"name"}
value={coop.name}
placeholder={"Enter cooperative name"}
handleChange={handleInput}
errors={errors}
/>
...
<Input
inputType={"text"}
title={"Street"}
name={"coop.addresses[0].formatted"}
value={coop.addresses[0].formatted}
placeholder={"Enter address street"}
handleChange={handleInput}
errors={errors}
/>
我尝试编写以下函数,但是我不知道如何在函数中引用“ coop”状态的通用属性。
const handleInput = (e) => {
let self = this;
let value = e.target.value;
let name = e.target.name;
if (name.indexOf("[") === -1) {
console.log("updating " + name + " with value:" + value);
setValue(coop, name, value);
} else {
const keys = name.split(/[\[\].]+/);
setCoop(updateValue(coop, keys, value));
}
};
const updateValue = (obj, name, value, index = 0) => {
if (name.length - 1 > index) {
const isArray = Array.isArray(obj[name[index]]);
obj[name[index]] = this.updateValue(
isArray ? [...obj[name[index]]] : { ...obj[name[index]] },
name,
value,
index + 1
);
} else {
obj = { ...obj, [name[index]]: value };
}
return obj;
};
...
const setValue = (obj, is, value) => {
console.log("setting " + is + " of value: " + value);
if (typeof is == "string") return setValue(obj, is.split("."), value);
else if (is.length === 1 && value !== undefined) {
return setCoop({ coop: obj[is[0]] = value });
} else if (is.length === 0) return obj;
else return setValue(obj[is[0]], is.slice(1), value);
};
这条线有麻烦
setCoop({ coop: obj[is[0]] = value });
如何引用“ coop”的通用属性及其值?
这个问题与钩子或React(其JavaScript)无关。
基本上,您询问如何在对象中设置通用密钥。
您应该为此使用实用程序功能,因为它不是简单的解决方案,请参见 lodash.set
设置对象路径处的值。如果路径的一部分不存在,则会创建它。为缺少的索引属性创建数组,而为所有其他缺少的属性创建对象。使用_.setWith自定义路径创建。
const object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
_.set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5
对于您的特定情况,假设obj[is[0]]
是您可以用来设置状态的路径。
但是请确保不要更改状态,将其视为不可变的,即_.set
在状态副本上使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句