具有多个动作/状态的 Redux connect()

Redux connect() with multiples actions / states

在 Redux 中将多个状态与相应的动作创建者连接起来的正确方法是什么?那是个好主意吗?如果这是一个愚蠢的想法,我该如何解决?

export default connect(

// which part of the Redux global state does
// our component want to receive as props?
(state) => {
  return {
    state: state.instagram
  };
},

// which action creators does
// it want to receive by props?
(dispatch) => {
  return {
    actions: bindActionCreators(instagramActions, dispatch)
  };
}

)(FeedContainer);

我基本上想要的是这样的:

...
state: {state.instagram, state.facebook}
...

...
const mergedActions = {instagramActions, facebookActions};
actions: bindActionCreators(mergedActions , dispatch)
...

使用提供的回调 mapStateTopProps 和 mapDispatchToProps 是将组件与已过滤的状态子集和已绑定的 actionCreators 连接起来的正确方法。

要实现你想要的,你可以简单地做:

(state) => {
  const { instagram, facebook } = state;
  return {
    state: { instagram, facebook }
  };
}

(dispatch) => {
  return {
     actions: bindActionCreators(Object.assign({}, instagramActions, facebookActions), dispatch)
  };
}

这不起作用:

actions: bindActionCreators({instagramActions, facebookActions} , dispatch)

因为该方法尚不支持嵌套对象。 See code here。 它只遍历键并查找函数。

在您的 mapDispatchToProps 回调中,您可以离开额外的状态层

(state) => {
   const { instagram, facebook } = state;
   return {
      instagram, 
      facebook
   };
}

通过这样做,您可以通过以下方式访问道具:

this.props.facebookthis.props.instagram 而不是 this.props.state.facebookthis.props.state.instagram。但这只是我认为的风格问题。

有几种方法可以绑定您的状态并分派给道具。归根结底,这是一个风格问题。我可以提供几个不同的例子来说明如何做,但最好看看官方文档并找到你自己的风格 https://github.com/reactjs/react-redux/blob/master/docs/api.md

或者您可以简单地这样做:

import * as todoActionCreators from './todoActionCreators'
import * as counterActionCreators from './counterActionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
  return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
  return {
    todoActions: bindActionCreators(todoActionCreators, dispatch),
    counterActions: bindActionCreators(counterActionCreators, dispatch)
  }
}

如 react-redux 文档所示

我知道这是一个老问题,但如果其他人想将所有操作映射到 this.props 中的一个键(像我一样),我在这里添加我的两分钱。

扩展 DavinTryon 对已接受答案的评论,实现“mergedActions”的另一种方法是使用扩展运算符,尤其是如果您想使用一个键(例如,actions)所有操作并使用 this.props.actions.[specificAction] 调用它们。以下是您必须在 connect 方法中执行的操作:

export default connect(
(state) => {
  return {
    state: state.instagram
  };
},

(dispatch) => {
  return {
    actions: bindActionCreators({...instagramActions, facebookActions}, dispatch)
  };
}

)(FeedContainer);

如果您单独声明方法(使用 mapDispatchToPropsmapStateToProps 之类的东西),您可以按如下方式编写 mapDispatchToProps

const mapDispatchToProps = dispatch => {
  return {
    actions: bindActionCreators({ ...instagramActions, facebookActions }, dispatch)
  };
};

这会将 facebookActionsinstagramActions 中的所有动作创建者映射到 this.props.actions