可能的方法是使用也mergeProps
该合并mapState
和mapDispatch
并允许使用两者在同一时间。
// Define mapState
const mapState = (state) => ({
needeedValue: state.neededValue
})
// Define mapDispatch
const mapDispatch = (dispatch, ownProps) => {
return {
onChange: (newValue, neededValue) => {
dispatch(updateAttributeSelection('genre', newValue));
dispatch(getTableData(newValue, ownProps.currentYear, neededValue));
}
}
}
// Merge it all (create final props to be passed)
const mergeProps = (stateProps, dispatchProps, ownProps) => {
return {
...stateProps, // optional
...dispatchProps, // optional
onChangeWithNeededValue: (newValue) => (
dispatchProps.onChange(
newValue,
stateProps.needeedValue // <<< here the magic happens
)
)
}
}
// Pass mergePros to connect
const MyContainer = connect(mapState, mapDispatch, mergeProps)(MyComponent);
正式文件:在大型应用程式react-redux#connect
可能的性能缺点:Stack Overflow - Performances and mergeProps in Redux
我认为真正的使用情况下,用于访问mapDispatchToProps状态是知道哪些行为是在运行时可用。例如,您可以将每个可能的操作映射到函数,并调用它来分派操作或使用if子句对其进行测试,以检查操作是否可用。 –