Is namespacing own-props separately from state-props a useful pattern?

痞子三分冷 提交于 2020-04-17 22:41:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!