2016-05-31 18 views
0

중첩 노드 트리가있는 앱이 있습니다. 모든 노드는 같은 유형입니다. 사용자가 어떤 노드를 확대redux 상태 트리 안에 새 데이터 추가

{ 
id: 1, 
title: "node_1", 
children: [ 
    { 
     id: 2, 
     title: "node_2", 
     children: [] 
    }, 
    { 
     id: 3, 
     title: "node_3", 
     children: [] 
    } 
] 

}

(ID 예는 노드 === 3) 나 "어린이"노드의 속성의 내부 데이터베이스에 요청을 수행하고 응답 (배열 어린이)을 삽입해야 id === 3. 그래서 결과적으로 응용 프로그램 상태는 다음과 같이해야합니다 :

{ 
id: 1, 
title: "node_1", 
children: [ 
    { 
     id: 2, 
     title: "node_2", 
     children: [] 
    }, 
    { 
     id: 3, 
     title: "node_3", 
     children: [ 
      { 
       id: 4, 
       title: "node_4", 
       children: [] 
      }, 
      { 
       id: 5, 
       title: "node_5", 
       children: [] 
      } 
     ] 
    } 
] 

}

은 내가 어떻게 node_3 어린이 속성 내 아이의 배열을 붙여 넣을 수 있습니다?

+0

https://github.com/reactjs/ REDUX/트리/마스터/예/트리보기 – ctrlplusb

답변

1

을 감안할 때 :

const layer1Id = 1; 
const layer2Id = 3; 
const newArray = [ 
    { 
    id: 4, 
    title: "node_4", 
    children: [], 
    }, 
    { 
    id: 5, 
    title: "node_5", 
    children: [], 
    } 
]; 

다음, 감속기에 당신이 할 수 있습니다 :

return Object.assign({}, state, { children: state.children.map(child => { 
    if (child.id !== layer1Id) return child; 
    return Object.assign({}, child, { children: child.children.map(node => { 
    if (node.id !== layer2Id) return node; 
    return Object.assign({}, node, { children: node.children.concat(newArray) }); 
    })}); 
})}); 

하기 이전 상태로 변이하지 않도록하려면. 동적으로 또는 깊게 중첩 된 경우 일부 재귀 함수를 작성하고 대신 사용하는 것이 좋습니다.

편집 : 여기에 재귀적인 샘플 솔루션 (테스트되지 않음)이 있습니다. indices 레벨에 의해 순서대로 (즉 : indices[0]은 첫 번째 수준의 ID를 참조, indices[1]는 두 번째 수준의 ID를 의미) :

const state = { ... }; 
const indices = [1, 3, 4, 5, 6]; 
const newArray = [ ... ]; 

const recursion = (node, ids, newChildren) => { 
    let children; 
    if (ids.length === 0) { 
    children = newChildren; 
    } else { 
    children = node.children.map(child => { 
     if (child.id !== ids[0]) return child; 
     return Object.assign({}, child, { children: recursion(child, ids.slice(1), newChildren) }); 
    }); 
    } 
    return Object.assign({}, node, { children }); 
}; 

recursion(state, indecies, newArray); 
내가보기 엔이 REDUX 트리의 예를보고하는 것이 좋습니다
+0

네, 깊이 중첩 될 것입니다. 이 상황과 일치 할 수있는 재귀 함수에 대한 링크를 추가 할 수 있습니까? –

+0

물론 시간을 좀주세요. – Kujira

+0

@PavelPoberezhnyi 재귀 적 솔루션을 추가했습니다. – Kujira

-1

배열을 통해 children 배열로 반복하고 하나를 수정합니다.

var id = expandedItemId; 
for(var i = 0; i < obj.children.length; i++){ 
    if(obj.id == expandedItemId){ 
    obj.children.push(`data got from server`); 
    } 
} 
+1

는 배열의 새로운 인스턴스를 반환하는 가장 좋은 방법은없는가요? – ctrlplusb

+0

미안합니다. @ctrlplusb이 무슨 뜻인지 몰랐습니다. 명확히 할 수 있겠습니까? – Ashot

+2

@ctrlplusb 예입니다. 그래서 if 문 안에 obj.children.concat ('서버로부터받은 데이터')와 같은 형태 여야합니다. – Kujira

1

돌아 오는 저장소에 관계형 또는 정규화 된 데이터에 대한 제안 된 접근 방식은 데이터베이스 테이블과 유사 "정규화"패션, 그것을 구성하는 것입니다. 업데이트를 쉽게 관리 할 수 ​​있습니다. http://redux.js.org/docs/FAQ.html#organizing-state-nested-data, How to handle tree-shaped entities in Redux reducers?https://github.com/reactjs/redux/pull/1269을 참조하십시오.

+0

덕분에 지금 이걸 읽을 것이다. –