在 React hooks 中,如何引用处于我想要更改的状态的对象的通用属性?

In React hooks, how do I refer to a generic attribute of an object in my state I want to change?

我正在为我的 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”的通用属性及其值?

这个问题与 hooks 或 React 无关,它 JavaScript。

基本上你问的是如何在对象中设置通用键。

您应该为此使用效用函数,因为它不是简单的解决方案,请参阅 lodash.set

Sets the value at path of object. If a portion of path doesn't exist, it's created. Arrays are created for missing index properties while objects are created for all other missing properties. Use _.setWith to customize path creation.

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]] 是您可以设置状态的路径。

但一定不要改变状态,treat it as immutable 即在状态副本上使用 _.set