我应该如何将大量的Redux操作从容器传递给表示组件?

时间:2016-12-18 09:32:35

标签: reactjs redux react-redux

我有以下连接到Redux商店的容器组件。我希望将六个动作传递给LayerList表示组件。

LayerListContainer.jsx

import React from 'react';
import { connect } from 'react-redux'
import LayerList from '../components/LayerList'

// import actions 
import * as LayerActions from '../actions/index'

export const LayerListContainer = ({ layers }) => (
    <div>
     <LayerList layers={layers} /* I want to pass actions to this component/>
    </div>
)

const mapStateToProps = state => ({
  layers: state.layers
})

// Use default export for the connected component (for app)
export default connect(mapStateToProps, LayerActions)(LayerListContainer)

以下是我希望通过的行动:

动作/ index.js

export const addLayer = (name) => ({
    type: ADD_LAYER,
    id: nextLayerId++,
    name,
})

export const removeLayer = (id) => ({
    type: REMOVE_LAYER,
    id
})

export const toggleDragLayer = (id) => ({
    type: TOGGLE_DRAG_LAYER,
    id
})

export const moveLayerIndex = (id, destinationIndex) => ({
    type: MOVE_LAYER_INDEX,
    id,
    destinationIndex
})

export const updateLayerColour = (id, colour) => ({
    type: UPDATE_LAYER_COLOUR,
    id,
    colour
})

export const toggleLayerVisibility = (id) => ({
    type: TOGGLE_LAYER_VISIBILITY,
    id
})

也许你不认为这是一个很大的行动。如果不是,我仍然有兴趣知道什么是最佳实践,以便将来参考从容器组件传递许多操作。

1 个答案:

答案 0 :(得分:0)

您可以使用...点差运算符语法将容器的每个属性传递给您的演示文稿

export const LayerListContainer = props => (
  <div>
    <LayerList {...props} />
  </div>
);

或者如果您只想传递操作,则必须使用bindActionCreators

import { bindActionCreators } from 'redux'

// ...

export const LayerListContainer = ({ layers, actions }) => (
  <div>
    <LayerList layers={layers} actions={actions} />
  </div>
);

// ..

const mapDispatchToProps = dispatch => ({ 
  actions: bindActionCreators(LayerActions, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(LayerListContainer)