상태

2017-05-10 3 views
2

에 배열 요소 (정수)를 교체 난 단지 정수로 구성된 간단한 배열을 가지고 : 나는 불변의 방법 (값 2에 값을 대체하기 위해 노력하고있어상태

this.state = { 
    myArray: [1,2,3] 
} 

교체해야합니다) 8 기준 :

const valueToReplace = 2 
const newValue = 8 
const myArray = this.state.myArray 
const arrayPosition = myArray.indexOf(valueToReplace) 
const newArray = Object.assign([], myArray, {arrayPosition: newValue}) 

this.setState({myArray: newArray}) 

하지만 내 방법은 상태에서 myArray를 변경하지 않습니다. Object.assign을 올바른 방법으로 사용하지 않는 것 같습니다.

답변

2

Array.prototype.slice을 사용하여 배열을 복사하고 복사본을 변형 한 다음 할당 할 수 있습니다. 기존 어레이를 수정하는 대신 새 어레이를 생성하기 때문에 돌연변이 문제는 여전히 안전합니다.

const valueToReplace = 2 
const newValue = 8 
const newArray = this.state.myArray.slice() // copy 
const arrayPosition = newArray.indexOf(valueToReplace) 
newArray[arrayPosition] = newValue 

this.setState({myArray: newArray}) 
1

먼저 배열의 복제를 생성하고 그 값을 대체하는 것이 낫다 : 다른 VAR로

const valueToReplace = 2 
const newValue = 8 
const myArray = this.state.myArray.slice(0); 
const arrayPosition = myArray.indexOf(valueToReplace) 
myArray[arrayPosition] = newValue 

this.setState({myArray: newArray}) 

Object.assign 단지 클론 객체/배열과 내의 값을 변경되지 정렬.