问题
Is the following pattern of namespacing state-provided props and parent-provided props a useful pattern?
interface OwnProps {
//The type for the props provided by the parent component
}
function mapDispatch(dispatch: Dispatch<any>) {
return {dispatch};
}
function mapState(state: RootState, ownProps: OwnProps) {
return {
o: {...ownProps}, // ownProps are namespaced onto o.
s: { // stateProps are namespaced onto s.
apiInReach: state.dev.apiInReach,
}
};
}
//// ...
export default connect(
mapState,
mapDispatch
)(Dev);
it seems like a good practice, but I haven't seen anyone use it.
Note how ownProps is namespaced onto "o" and stateProps are namespaced onto "s" in mapState().
回答1:
It's no problems there in my opinion.
By the way, we can make it a clear view by passing Type in a method as below
interface Props extends WithStyles<typeof styles> {
classes: any,
parentProps1: TypeOfParentProps1,
parentProps2: TypeOfParentProps2,
...
stateProps1: Store['stateName1'], // Use `[]` to distinguish from above
stateProps2: Store['stateName2'],
...
actionDispatched: (payload: TypeOfActionPayload) => void,
...
Since you must have defined the redux store Type in somewhere else, call it would be as good as the normal way.
// Redux store defination
export interface Store {
stateName1: TypeOfStateProps1,
stateName2: TypeOfStateProps2,
...
回答2:
Looks like this can only be effectively done using mergeProps:
interface OwnProps {
//The type for the props provided by the parent component
}
function mergeProps(state: RootState, dispatch: Dispatch<any>, ownProps: OwnProps) {
return {
dispatch,
o: ownProps, // ownProps are namespaced onto o.
s: { // stateProps are namespaced onto s.
apiInReach: state.dev.apiInReach,
}
};
}
//// ...
export default connect(
null,
null,
mergeProps
)(Dev);
the documentation for mergeProps is here: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#mergeprops-stateprops-dispatchprops-ownprops--object
来源:https://stackoverflow.com/questions/60556355/is-namespacing-own-props-separately-from-state-props-a-useful-pattern