如何更新数组内对象属性的值?

时间:2020-04-22 06:39:39

标签: reactjs react-hooks

 const seconDarydata = [
    { value: 1, label: "desc1" },
    { value: 2, label: "desc2" },
    { value: 3, label: "desc3" },
    { value: 4, label: "desc4" },
    { value: 5, label: "desc5" },
    { value: 6, label: "desc6" }
  ];
  const primarydata = [{ value: 1, label: "primaryAdd1" }];

  const [primaryAdd, setPrimayAdd] = useState(primarydata);
  const [secondaryAdd, setSecondaryAdd] = useState(seconDarydata);


const onClickHandler = index => {
    let oldPrimatLocations = primaryAdd;
    let newPrimaryLocation = secondaryAdd[index];
    
    let objIndex = secondaryAdd.findIndex(
      obj => obj.value === oldPrimatLocations[0].value
    );

    secondaryAdd[objIndex + 1].label = oldPrimatLocations[0].label;
    setPrimayAdd([newPrimaryLocation]);
    setSecondaryAdd(secondaryAdd);
  };
  

<div>
      <h5>Primay Data</h5>
      <h6>{primaryAdd[0].label}</h6>
      <h6>Secondary Data</h6>
      {secondaryAdd.map((item, index) => {
        return (
          <div>
            {index}
            <button id={item.value} onClick={() => onClickHandler(index)}>
              {item.label}
            </button>
          </div>
        );
      })}
    </div>
    

我有两个数组,并在useState中将此数组使用初始状态。 我的目标是实现交换功能。

因此在这里,如果用户单击secondaryData,它将与主要数据交换。 我尝试了所有的东西,但是缺少了一些东西。 有人可以让我知道onClickHandler缺少什么条件。 有可能使用...运算符。

谢谢

1 个答案:

答案 0 :(得分:0)

问题是您正在突变状态对象:

const onClickHandler = index => {
  let oldPrimatLocations = primaryAdd;
  let newPrimaryLocation = secondaryAdd[index];

  let objIndex = secondaryAdd.findIndex(
    obj => obj.value === oldPrimatLocations[0].value
  );

  secondaryAdd[objIndex + 1].label = oldPrimatLocations[0].label; // mutate state and mix up index
  setPrimayAdd([newPrimaryLocation]);
  setSecondaryAdd(secondaryAdd); // saved mutate state reference back in state
};

解决::如果我正确理解,如果“ primaryAdd1”在主数组中,并且用户单击“ desc3”,则这两个值会互换。现在“ desc3”在主数组中,而“ primaryAdd1”在辅助数组中的索引为2。

primary: ["desc3"]
secondary: ["desc1", "desc2", "primaryAdd1", "desc4", "desc5", "desc6"]

如果用户现在单击“ desc6”,它将交换并且现在位于主数组中,而“ desc3”位于辅助数组中的索引5。

primary: ["desc6"]
secondary: ["desc1", "desc2", "primaryAdd1", "desc4", "desc5", "desc3"]

解决方案:提取旧的和新的主位置对象,将newPrimaryLocation放置在主数组中,并将oldPrimaryLocation放置在辅助数组相同的索引

const onClickHandler = index => {
  const oldPrimaryLocation = primaryAdd[0];
  const newPrimaryLocation = secondaryAdd[index];

  setPrimaryAdd([newPrimaryLocation]);
  setSecondaryAdd(secondaryAdd =>
    // functional update and map to return new array reference
    secondaryAdd.map((el, i) => (i === index ? oldPrimaryLocation : el))
  );
};

Edit delicate-pond-p72wl

不同的实现方式是先复制阵列,进行交换,然后仅将复制的阵列保存在状态中。

const onClickHandler = index => {
  const primary = [...primaryAdd];
  const secondary = [...secondaryAdd];

  [secondary[index], primary[0]] = [primary[0], secondary[index]];

  setPrimaryAdd(primary);
  setSecondaryAdd(secondary);
};