2017-03-28 65 views
0

我有表部件,這使得行的項目列表:陣營Redux的元件不更新

return <Row style={styles.row} key={idx} item={item} onSelect={this.props.onRowSelect}> 
    {columns.map((col, idx) => { 
     return <Column style={col.style} key={`${item._id}_${col.key}`} 
         width={col.width || this._defaultCellWidth} type={col.type}> 
      {_.get(item, col.key)} 
     </Column> 
    })} 
    </Row> 

每個項目都有selected:bool值,它被綁定到每一行的複選框。

此外,我有一個HeaderRow,其中有選擇全部複選框。 通過選中複選框,我派遣一個事件來更新所選字段。 狀態本身已更新,但沒有重置。 我的動作是:

if(action.id) 
{ 
    let index = state.items.findIndex(item => item._id == action.id); 
    state.items[index].selected = action.selected; 
} 
else 
{ 
    state.items.map(e=>e.selected = action.selected); 
} 

return 
{ 
    ...state, 
    items: state.items 
} 

編輯: 那是很好的解決方案:

if(action.id) { 
      let index = state.items.findIndex(item => item._id == action.id); 
      state.items[index].selected = action.selected; 
      return { 
       ...state 
      } 

     }else{ 
      return { 
       ...state, 
       items: state.items.map((item, index) => { 
        return Object.assign({}, item, { 
         selected: action.selected 
        }) 
       }) 
      } 
     } 

回答

0

只是經常發生的常見錯誤。看看this article,因爲它解釋瞭如何安全地更新每種級別。

在你的情況下,應該是這樣的:

return 
{ 
    // Copy the current state 
    ...state, 
    // Replace the items array with a new version, 
    // by creating a new array through the map() call. 
    items: state.items.map((item, index) => { 
     // This isn't the item in the array we are looking 
     // for. So simply return it as is. 
     if(index != action.id) { 
      return item; 
     } 

     // This is the item to be changed. So copy it and 
     // overwrite the selected property. 
     return { 
      ...item, 
      selected: action.selected 
     }; 
    }); 
} 
+0

不起作用,因爲現在所有的行正在渲染(我在行渲染函數中引用它)。所以我想現在它認爲所有的項目都改變了。 – user3712353

+0

然後你必須進一步分解你的容器和組件。也許你應該看看[這個視頻](https://www.youtube.com/watch?v=KYzlpRvWZ6c)或[這個組件](https://facebook.github.io/fixed-data-table/ )。 – Oliver