Javascript和React设置数组中数组的状态并使用扩展运算符
我使用react并希望创建一个项目数组,然后使用spread运算符,但设置起来有困难Javascript和React设置数组中数组的状态并使用扩展运算符,javascript,reactjs,react-native,react-hooks,use-state,Javascript,Reactjs,React Native,React Hooks,Use State,我使用react并希望创建一个项目数组,然后使用spread运算符,但设置起来有困难 const [mediaArray, setMediaArray] = useState(null); const [newArray, setNewArray] = useState([]); const handleNewSet = index => { setNewArray([...newArray[index], '']); mediaArray[index] = { ...m
const [mediaArray, setMediaArray] = useState(null);
const [newArray, setNewArray] = useState([]);
const handleNewSet = index => {
setNewArray([...newArray[index], '']);
mediaArray[index] = {
...mediaArray[index],
['sets']: [...newArray[index], ''],
};
};
获取错误:TypeError:传播不可编辑实例的尝试无效
我有一个按钮,它将从newArray
向mediaArray
添加额外的集合数组。但是,由于我正在尝试遍历mediaArray
,因此我希望确保正确的集合指向正确的mediaArray。我希望这是有道理的
所以我最终会有一组mediaArray和一组集合
mediaArray = {
sets: ['data1', 'data2', ...] //this will be from a specific index of the newArray
}
mediaArray = {
sets: ['bb1', 'bb2', bb3, ...] //this will be from a specific index of the newArray
}
另一个mediaArray与另一组集合
mediaArray = {
sets: ['data1', 'data2', ...] //this will be from a specific index of the newArray
}
mediaArray = {
sets: ['bb1', 'bb2', bb3, ...] //this will be from a specific index of the newArray
}
等等
最终,我希望有一个新的阵列:
newArray = [['data1','data2', ...], [bb1, bb2, bb3, ...], [aa2, aa5, ...], [...]]
我看到的第一个问题是,使用
null
初始化mediaArray
:const[mediaArray,setMediaArray]=useState(null)
但您正试图访问它的索引,该索引已在handleNewSet
中。您尚未共享完整的代码,因此我假设您正在其他地方将其设置为空数组,如果没有:请确保这样做
我现在只是猜测,mediaArray[index]
是undefined
并且传播它将抛出一个错误,即不能传播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);
};
很抱歉,我很难理解,您能为您的变量显示所需的数据类型吗?这应该会让事情缓和一点。