我在组件上两次致电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'
有什么想法吗?
答案 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
。