javascript - 如何结合使用 connect() 的两种用法?

标签 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);

但我收到此错误:

Uncaught TypeError: Cannot read property 'pagination' of undefined

或者这个:

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

但我明白了:

Uncaught TypeError: Cannot read property 'softlayerAccountId' of undefined

有什么想法吗?

最佳答案

你搞错了。 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

关于javascript - 如何结合使用 connect() 的两种用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115202/

相关文章:

javascript - 为什么数组上的 .toString 会给出奇怪的结果?

javascript - 了解 jQuery 中更改事件中 'this' 的范围

Golang 与 React 路由器?

JavaScript:在模板变量内添加 if 条件

javascript - 单击时从 'display : none' 过渡到 'display:inline'

javascript - 使用 JavaScript 应用 DRY 原则

reactjs - 验证 Redux Store 中的数据

javascript - 我可以避免在路由更改时重新渲染父路由处理程序组件吗?

javascript - 在 JavaScript 中继续之前等待函数完成

javascript - 如何将变量传递给子组件以便它们与 React Router 一起使用?