在redux reducer中更新数组时,React不会重新渲染

时间:2018-01-11 13:35:19

标签: javascript arrays reactjs react-redux

我有一个处于reducer初始状态的数组。我将它传递给组件,我只是通过从组件调度一个动作,将一个数组元素移动到reducer中数组内的不同索引。我能够看到数组中的变化,但它不会在屏幕上重新渲染。

import * as actionTypes from './actionTypes'
import _ from 'lodash'

const initialState = {
    columnDefs: [
       { key: 'a', name: 'Order', width: 120},
       { key: 'b', name: 'Supplier'width: 100},
       { key: 'c', name: 'Article', width: 100}
    ]
}

export default function reduce (state = initialState, action = {}) {
   case actionTypes.UPDATE_COLUMNS: {
      let columnDefs = _.cloneDeep(state.columnDefs)
      columnDefs.splice(
        action.data.columnTargetIndex,
        0,
        columnDefs.splice(action.data.columnSourceIndex, 1)[0]
      )
      return { ...state, columnDefs }
  }

  default:
    return state
}
}

Component使用源索引和目标索引调度操作。

  onUpdate (source, target) {
      const columnSourceIndex = this.state.columnDefs.findIndex(
         i => i.key === source
      )
      const columnTargetIndex = this.state.columnDefs.findIndex(
         i => i.key === target
      )
      this.props.updateColumns({columnSourceIndex, columnTargetIndex})
  }

内部组件的渲染

    <DraggableContainer onHeaderDrop={this.onUpdate}>
        <ReactDataGrid
            columns={this.state.columnDefs}
            rowGetter={rowGetter}
            rowsCount={_rows.length}
            rowHeight={40}
            onRowClick={this.props.onRowClick}
            emptyRowsView={NoDataView}
            onGridRowsUpdated={this.handleGridRowsUpdated}
        />
    </DraggableContainer>

连接组件

      function mapStateToProps (state, ownProps) {
        const { columnDefs, selectedRows } = state.FOL
        return ({ columnDefs, selectedRows })
      }

      function mapDispatchToProps (dispatch) {
        return ({
          updateColumns: (data) => { dispatch(updateColumns(data)) }
        })
      }

      export default connect(mapStateToProps, mapDispatchToProps)(FOLContainer)

提前致谢。

此致 Rinkesh

0 个答案:

没有答案