2017-10-03 7 views
0

나는 sortable 테이블의 역할을하는 React 컴포넌트를 가지고있다. 테이블 헤더와 테이블 행은 컨테이너의 하위이며 컨테이너는 테이블의 상태를 처리합니다. 헤더를 클릭하면 데이터는 this semantic-ui-react example처럼 다시 정렬됩니다.React 하위 구성 요소가 새 소품을받지 않는 이유는 무엇입니까?

handleSort = (clickedColumn) => { 
const { column, orders, direction } = this.state 

if (column !== clickedColumn) { 
    this.setState({ 
    column: clickedColumn, 
    orders: customSort(orders, clickedColumn), 
    direction: 'ascending', 
    }) 
} else { 
this.setState({ 
    orders: orders.reverse(), 
    direction: direction === 'ascending' ? 'descending' : 'ascending', 
})} 

내가 열 머리글을 클릭 처음으로, 최초의 폐쇄 실행하고 this.setState 컨테이너의 상태를 변경하고 새로운 소품을 받고 그에 따라 업데이트 할 아이들을 트리거합니다. 열 머리글을 다시 클릭하여 데이터 순서를 바꾸면 두 번째 클로저가 실행되고 this.setState은 컨테이너의 상태를 업데이트합니다. 따라서 하위 구성 요소 OverviewTableHeader은 업데이트되지만 OverviewTableRows은 업데이트되지 않습니다.

render() { 
const { designers, orders, column, direction } = this.state 
if (orders === "loading"){ 
    return <Loading /> 
} 
const tableRows = <OverviewTableRows 
        designers={designers} 
        orders={this.state.orders} 
        /> 
debugger 
return (
    <div className="overview"> 
    <Table selectable fixed sortable> 
     <OverviewTableHeader sort={this.handleSort} column={column} direction={direction}/> 
     {tableRows} 
    </Table> 
    </div> 
) 
} 
비디오에서

Here's a video of this in action.

, 당신은 OverviewTableRows 트리거 componentWillReceivePropsshouldComponentUpdate setState 부모에 트리거 처음,하지만 두 번째를 볼 수 있습니다.

필요한 경우 모든 코드를 추가 할 수 있습니다. 이거 버그 야? 어떤 도움이라도 대단히 감사합니다!

답변

1

나는 그것을 역전시키기 전에 배열의 복사본을 만들고 그것을 사용하여 상태를 업데이트함으로써 이것을 해결했다.

handleSort = (clickedColumn) => { 
const { column, orders, direction } = this.state 

if (column !== clickedColumn) { 
    this.setState({ 
    column: clickedColumn, 
    orders: customSort(orders, clickedColumn), 
    direction: 'ascending', 
    }) 
} else { 
    const reversedOrders = orders.slice().reverse(); 
this.setState({ 
    orders: reversedOrders, 
    direction: direction === 'ascending' ? 'descending' : 'ascending', 
})} 

배열의 신원은 orders입니다. 나는 이것이 React의 기능적 본질과 관련이 있다고 생각합니다. 이 사람이 도움이되기를 바랍니다! 아무도 이것이 왜 그런지에 대한 좋은 설명이 있다면, 나는 그것을 듣고 싶습니다.

0

무슨 일이 일어나는지 설명하는 좋은 인용구가 있습니다.

this.state를 직접 조작하면 잠재적으로 위험 할 수있는 React의 상태 관리를 우회하고 있습니다. 나중에 setState()를 호출하면 변경 한 돌연변이가 바뀔 수 있습니다.

취지 : this article. orders 이후

(이 재정렬이 setState 호출 내에서 수행되는 경우에도) 당신이 orders.reverse를 호출 할 때 변경 가능한 객체와 state의 멤버가 직접 상태를 변경하는 것입니다.

그래, this.state을 직접 변경하지 않으므로 예, orders 복사본을 만드는 방법으로이 문제를 해결할 수 있습니다.