如何合并connect()的2种用法?

时间:2019-01-09 17:11:18

标签: javascript reactjs ecmascript-6 redux

我在组件上两次致电connect(),代码审查员要求我将其设置为一个。

我有这可以按预期工作:

export default compose(
  connect(store => ({
    softlayerAccountId: store.global.softlayerAccountId,
  })),
  connect(
    ({ shipments }) => ({
      pagination: shipments.pagination,
      isFiltersModalOpened: shipments.filtersModalOpened,
      filters: shipments.filters,
    }),
    dispatch => ({...}),
  ),
)(GetShipments);

他们希望我做这样的事情:

export default compose(
  connect(
    store => ({
      softlayerAccountId: store.global.softlayerAccountId,
    }),
    ({ shipments }) => ({
      pagination: shipments.pagination,
      isFiltersModalOpened: shipments.filtersModalOpened,
      filters: shipments.filters,
    }),
    dispatch => ({...}),
  ),
)(GetShipments);

但是我得到这个错误:

  

未捕获的TypeError:无法读取未定义的属性“分页”

或者这个:

export default compose(
  connect(
    ({ shipments }, store) => ({
      softlayerAccountId: store.global.softlayerAccountId,
      pagination: shipments.pagination,
      isFiltersModalOpened: shipments.filtersModalOpened,
      filters: shipments.filters,
    }),
    dispatch => ({...}),
  ),
)(GetShipments);

但是我明白了:

  

未捕获的TypeError:无法读取未定义的属性'softlayerAccountId'

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您错了。 connect()接受两个参数:mapStateToProps回调和mapDispatchToProps。在第二个变体中,您尝试传递3个参数,其中第二个实际上也指向存储(因此,就像您将mapStateToProps放在mapDispatchToProps上一样)。

您需要它具有2个参数:

export default compose(
  connect(
    ({global: {softlayerAccountId}, shipments }) => ({
        softlayerAccountId: store.global.softlayerAccountId,
        pagination: shipments.pagination,
        isFiltersModalOpened: shipments.filtersModalOpened,
        filters: shipments.filters,
    }),
    dispatch => ({...}),
)(GetShipments);

为什么第三个变体不起作用?相同的原因:您试图将参数放在无法工作的地方。

({ shipments }, store) => ({

在此声明带有两个参数的函数。首先是解构,其次才传入。但是connect仅传递store的单个参数。仅仅因为您期望,它不会多次通过store