简体   繁体   中英

How can I combine 2 uses of connect()?

I am calling connect() twice on my component and a code reviewer asked me to make it to one.

I have this which works as expected:

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

And they want me to do something like this:

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

But I get this error:

Uncaught TypeError: Cannot read property 'pagination' of undefined

Or this:

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

But I get this:

Uncaught TypeError: Cannot read property 'softlayerAccountId' of undefined

Any ideas?

you are making it wrong. connect() takes two arguments: mapStateToProps callback and mapDispatchToProps . In you second variant your are trying to pass 3 arguments where 2nd actually also refers to store(so it's like you put mapStateToProps onto mapDispatchToProps place).

You need it to have 2 arguments:

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

Why 3rd variant does not work? The same reason: you are trying to put arguments where there are cannot work.

({ shipments }, store) => ({

Here you declare function that takes two arguments. First is destructuring and second is just passed in. But connect will pass just single argument of store . It will not pass store for several times just because you expect that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM