2017-10-03 10 views
0

私は、ソート可能なテーブルとして機能する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は、コンテナの状態を変更し、新しい小道具を受信し、それに応じて更新するために、子どもたちをトリガーします。列のヘッダーを再度クリックしてデータの順序を逆にすると、2番目のクロージャが実行され、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 articleordersので

が可変オブジェクトとstateのメンバーであるあなたはorders.reverseを呼び出すときには、(このリオーダリングがsetStateコール内で行われている場合でも)、直接状態を変更しています。

ordersのコピーを作成すると、this.stateを直接変更する必要がなくなり、この問題は解決されます。

関連する問題