React setState of for 深度嵌套的值

IT技术 javascript reactjs javascript-objects setstate
2021-05-24 18:54:51

我的 React 状态中有一个非常深的嵌套对象。目的是更改子节点的值。应该更新哪个节点的路径已经解决了,我使用辅助变量在我的 setState 中访问这个路径。

无论如何,我真的很难在这个嵌套的野兽中执行 setState 。我在代码笔中抽象了这个问题:https ://codesandbox.io/s/dazzling-villani-ddci9

在此示例中,我想更改changed具有id def1234.

如前所述,给出了路径:固定路径值:Members, skills和变量路径值:(Unique Key 1来自const currentGroupKey和数据中的两个数组位置来自const path

这是我的状态对象:

constructor(props) {
  super(props);
  this.state = { 
    group:
    {
      "Unique Key 1": {
        "Members": [
          {
            "name": "Jack",
            "id": "1234",
            "skills": [
              {
                "name": "programming",
                "id": "13371234",
                "changed": "2019-08-28T19:25:46+02:00"
              },
              {
                "name": "writing",
                "id": "abc1234",
                "changed": "2019-08-28T19:25:46+02:00"
              }
            ]
          },
          {
            "name": "Black",
            "id": "5678",
            "skills": [
              {
                "name": "programming",
                "id": "14771234",
                "changed": "2019-08-28T19:25:46+02:00"
              },
              {
                "name": "writing",
                "id": "def1234",
                "changed": "2019-08-28T19:25:46+02:00"
              }
            ]
          }
        ]
      }
    }
  };
}

handleClick = () => {
  const currentGroupKey = 'Unique Key 1';
  const path = [1, 1];
  // full path: [currentGroupKey, 'Members', path[0], 'skills', path[1]]
  // result in: { name: "writing", id: "def1234", changed: "2019-08-28T19:25:46+02:00" }

  // so far my approach (not working) also its objects only should be [] for arrays
  this.setState(prevState => ({
    group: {
      ...prevState.group,
      [currentGroupKey]: {
        ...prevState.group[currentGroupKey],
        Members: {
          ...prevState.group[currentGroupKey].Members,
          [path[0]]: {
            ...prevState.group[currentGroupKey].Members[path[0]],
            skills: {
              ...prevState.group[currentGroupKey].Members[path[0]].skills,
              [path[1]]: {
                ...prevState.group[currentGroupKey].Members[path[0]].skills[
                  path[1]
                ],
                changed: 'just now',
              },
            },
          },
        },
      },
    },
  }));
};

render() {
  return (
    <div>
      <p>{this.state.group}</p>
      <button onClick={this.handleClick}>Change Time</button>
    </div>
  );
}

我将不胜感激任何帮助。我已经挣扎了 2 天了:/

2个回答

在使用新的依赖项并必须学习它们之前,您可以编写一个辅助函数来处理更新深度嵌套的值。

我使用以下助手:

//helper to safely get properties
// get({hi},['hi','doesNotExist'],defaultValue)
const get = (object, path, defaultValue) => {
  const recur = (object, path) => {
    if (object === undefined) {
      return defaultValue;
    }
    if (path.length === 0) {
      return object;
    }
    return recur(object[path[0]], path.slice(1));
  };
  return recur(object, path);
};
//returns new state passing get(state,statePath) to modifier
const reduceStatePath = (
  state,
  statePath,
  modifier
) => {
  const recur = (result, path) => {
    const key = path[0];
    if (path.length === 0) {
      return modifier(get(state, statePath));
    }
    return Array.isArray(result)
      ? result.map((item, index) =>
          index === Number(key)
            ? recur(item, path.slice(1))
            : item
        )
      : {
          ...result,
          [key]: recur(result[key], path.slice(1)),
        };
  };
  const newState = recur(state, statePath);
  return get(state, statePath) === get(newState, statePath)
    ? state
    : newState;
};

//use example
const state = {
  one: [
    { two: 22 },
    {
      three: {
        four: 22,
      },
    },
  ],
};
const newState = reduceStatePath(
  state,
  //pass state.one[1],three.four to modifier function
  ['one', 1, 'three', 'four'],
  //gets state.one[1].three.four and sets it in the
  //new state with the return value
  i => i + 1 // add one to state.one[0].three.four
);
console.log('new state', newState.one[1].three.four);
console.log('old state', state.one[1].three.four);
console.log(
  'other keys are same:',
  state.one[0] === newState.one[0]
);

如果您需要更新状态内部的深层嵌套属性,则可以使用类似setfrom函数lodash,例如:

import set from 'lodash/set'

// ...

handleClick = () => {
  const currentGroupKey = 'Unique Key';
  const path = [1, 1];

  let nextState = {...this.state}

  // as rightly pointed by @HMR in the comments,
  // use an array instead of string interpolation
  // for a safer approach

  set(
    nextState,
    ["group", currentGroupKey, "Members", path[0], "skills", path[1], "changed"],
    "just now"
  );

  this.setState(nextState)
}

这可以解决问题,但由于set改变了原始对象,请确保使用该object spread技术制作副本


此外,在您的CodeSandbox示例中,您将group内部属性设置state为字符串。确保您使用该JSON字符串并用它构建一个合适的 JavaScript 对象,以便您可以在您的状态下使用它。

constructor(props) {
  super(props)
  this.setState = { group: JSON.parse(myState) }
}

这是一个工作示例: