使用嵌套级别的对象和数组动态更新状态

Update state dynamically with nested levels of objects and array

这就是问题所在

我正在尝试更新这个名为 singleCarers 的对象的状态

我在花名册数组中有花名册的索引,我需要更新

但是 The key monday: 需要动态 & key start: & finish: 也需要动态

const indexOfRoster = index;

const dayOfRoster = day;

const { value, name } = e.target;  // name represents either start: or finish: & value is the value of start or finish eg. name:value === start: "09:10"



{
  "rosters": [
    {
       
        "schedule": {

            "monday": {

                "start": "",
                "finish": "",

            },
        },

    },
]
}


你有两个问题:

  1. 您需要使用 Computed property names
  2. 引用对象
  3. 在设置状态下使用回调需要您 return 函数的新状态。
setSingleCarers((prevState) => {
  const updatedRosters = prevState.rosters.map((roster, index) => (
    index === indexOfRoster
      ? {  // update the target roster
          ...roster,
          schedule: {
            ...roster.schedule,
            [dayOfRoster]: {
              ...roster.schedule[dayOfRoster],
              [name]: value,
            },
          },
        }
      : roster,
  ));

  return {  // return the new State
    ...prevState,
    rosters: updatedRosters,
  };
}

这可能看起来有些过分,在这种情况下,您可以研究解决方案,例如 immer 或其他使此类对象操作更容易的库,而不必记住进行深度对象复制

不要想太多,如果你不使用复杂的数据类型,这是最好的选择

JSON.parse(JSON.stringify(object))

const auxState = JSON.parse (JSON.stringify(reactState))

// now modify auxState
auxState[index][day]={
 start:"val",
 end:"val"
}

setReactState(auxState)

如果你想变漂亮

function clone(obj) {
    if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    if (obj instanceof Date)
        var temp = new obj.constructor(); //or new Date(obj);
    else
        var temp = obj.constructor();

    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }
    return temp;
}

const auxState = clone(reactState)
// Modify auxState

setReactState (auxState)