그래서 React를 처음 사용했습니다. 함수 맵을 사용하여 Component 상태의 객체 배열에 ID를 제공하려고합니다. 그러나 함수의 객체를 반복 할 때 결과로 생성 된 배열의 요소는 모두 동일하며 마지막으로 반복 된 요소와 같습니다. 고유 ID를 추가하기 위해 uuid 모듈을 사용하고 있습니다. 이것은 내가 코멘트 안에 더 나은 설명과 함께 Component 내부에있는 것입니다 :React에서 맵을 사용하면 마지막 요소와 동일한 배열이 반환됩니다.
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)
}
어떤 도움을 주시면 감사하겠습니다. 감사.
'배열 #의 fill'은 동일하게 배열의 모든 요소를 설정하는 것입니다 개체이므로 가장 최근의 변경은 개체에 포함 된 것입니다. – 4castle
@ 4castle 응답에 감사드립니다. 하지만 난 단지 한 번만 생성자에서 사용하는 경우, 그것은 정확하게 동일하지 않을 모든 이들을 위해 setState를 사용하고 있어도 영향을 미칠까요? –