【问题标题】:Javascript and React setting state of arrays within arrays and using spread operatorJavascript和React在数组中设置数组状态并使用扩展运算符
【发布时间】:2020-03-12 16:46:21
【问题描述】:

我使用 react 并想创建一个项目数组,然后使用扩展运算符,但我无法设置它。

const [mediaArray, setMediaArray] = useState(null);
const [newArray, setNewArray] = useState([]);

const handleNewSet = index => {
  setNewArray([...newArray[index], '']);
  mediaArray[index] = {
    ...mediaArray[index],
    ['sets']: [...newArray[index], ''],
  };
};

得到错误:TypeError: Invalid attempt to spread non-iterable instance

我有一个按钮,它将从newArray 添加额外的集合数组到mediaArray。但是因为我试图遍历mediaArray,所以我想确保正确的sets 进入正确的mediaArray。我希望这是有道理的

所以我最终会有 1 组 mediaArray 和 1 组集

mediaArray = {
  sets: ['data1', 'data2', ...] //this will be from a specific index of the newArray
}

另一个带有另一组集合的 mediaArray

mediaArray = {
  sets: ['bb1', 'bb2', bb3, ...] //this will be from a specific index of the newArray
}

等等……

最终我想要newArray:

newArray = [['data1','data2', ...], [bb1, bb2, bb3, ...], [aa2, aa5, ...], [...]]

【问题讨论】:

  • 很抱歉,我很难理解,您能否为您的变量显示所需的数据类型?这应该会缓解一点。

标签: javascript reactjs react-native react-hooks use-state


【解决方案1】:

我看到的第一个问题是你用null:const [mediaArray, setMediaArray] = useState(null); 初始化你的mediaArray,但是你试图访问它已经在handleNewSet 中的index。您尚未共享完整代码,因此我假设您将其设置为其他地方的空数组,如果没有:请确保您这样做!

我现在只是猜测mediaArray[index]undefined 并且传播它会抛出你不能传播未定义的错误。

尝试以下代码更改:

const [mediaArray, setMediaArray] = useState(null);
const [newArray, setNewArray] = useState([]);

const handleNewSet = index => {
  setNewArray([...newArray[index], '']);

  // clone array for state update
  const newMediaArray = [...mediaArray];

  // check if there is already this index in mediaArray
  if(mediaArray[index]) {
    // update index
    newMediaArray[index] = {
       ...mediaArray[index],
       ['sets']: [...newArray[index], ''],
    };
  } else {
   // create index in array
   newMediaArray[index] = {
       ['sets']: [...newArray[index], ''],
    };
  }
  // finally update state
  setMediaArray(newMediaArray);
};

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2019-09-01
    • 2018-05-17
    • 2018-02-16
    • 2021-03-25
    • 2018-12-25
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多