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

How should I pass a large amount of Redux actions from a container to presentational component?

我有以下连接到 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)

以下是我希望通过的操作:

actions/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
})

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

您可以使用像这样的 ... 扩展运算符语法将容器的每个属性传递给演示文稿

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)