gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:22:26 25 4
gpt4 key购买 nike

我在组件上调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com