다른 개체 내에 중첩 된 두 개체를 포함하는 내 redux 상태의 일부를 업데이트하려고합니다. 일반적으로 javascript 객체를 변경하지 않고 업데이트 할 때 스프레드 연산자를 사용한 다음 변경 사항을 다음과 같이 정의합니다.
state = {...state, property1: newvalue}
그러나 중첩 된 개체가있을 때 스프레드 연산자를 사용하는 방법을 잘 모르겠습니다. 다음은 관련 코드와 내 시도입니다.
const squadDatabase = {currentSquad: {
0: null,
1: null,
2:null
}, newAdditions: null}
export default (state=initial_squad, action)=>{
switch(action.type){
case ADD_PLAYER_TO_SQUAD:
return {...state, currentSquad[action.payload.currentSquadMemberId]:action.payload.newSquadAdditionId, newAdditions: action.payload.newSquadAdditionId}
default:
return initial_squad
}
}
누구든지 스프레드 연산자 또는 기타를 사용하여 중첩 된 자바 스크립트 객체를 변경없이 업데이트하는 방법을 알고 있습니까?
기본적으로 두 번째 수준의 객체 (상태) 분해를 추가해야합니다.
return {
...state, // first nesting level spread
currentSquad: {
...this.state.currentSquad, // second nesting level spread
currentSquad[action.payload.currentSquadMemberId]: action.payload.newSquadAdditionId,
},
newAdditions: action.payload.newSquadAdditionId,
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다