所以我是 React 的新手。我正在尝试使用函数映射为处于组件状态的对象数组提供一个 id。但是当我遍历函数中的对象时,结果数组的元素彼此相等,等于最后一个迭代的元素。我正在使用 uuid 模块添加唯一 ID。这是我在组件内部的内容,在注释中有更好的解释:
constructor() {
super()
this.state = {
classes: Array(5).fill({
id: null,
name: null
}),
}
}
componentWillMount() {
// This console.log, strangely, logs the state of the Component as if
// this componentWillMount function had already been executed, showing the
// classes with their ids (still the wrong ones). Would appreciate it if
// someone explained that
console.log(this.state.classes)
let classThings = this.state.classes.map(classObject => {
let obj = classObject
obj.id = uuid.v4()
// This logs the object correctly. The console shows, thanks to this,
// five different objects with five different ids
console.log(obj)
return obj
})
this.setState({
classes: classThings
})
// But, for some reason, this one logs the array and all the elements
// inside are equal to te last one logged by the previous console.log
// that is inside the map function, when it should log an array with the
// five different elements
console.log(classThings)
}
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
数组 classes
中的每个元素都指向同一个对象(因为 Array.fill
只是将数组中的每个元素设置为您传递给它的单个对象),所以当您对 classes
中的任何对象进行更改时,您将更改 classes
中的每个对象。您可以使用 map
为每个元素创建一个新对象:
替换
Array(5).fill({
id: null,
name: null
})
与
Array(5).fill(null).map(() => ({
id: null,
name: null
}))
通过此更改,您还可以在创建 classes
中的每个对象时为其指定一个唯一 ID,而不是在 componentWillMount
中:
Array(5).fill(null).map(() => ({
id: uuid.v4(),
name: null
}))
关于javascript - 在 React 中使用 map 返回一个等于最后一个元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48012604/