本文介绍了将自己的道具与状态道具分开命名空间是一种有用的模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下命名空间状态提供的 props 和父提供的 props 的模式有用吗?

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.

注意 ownPropsmapState() 中如何命名空间为o",stateProps 命名空间为s".

Note how ownProps is namespaced onto "o" and stateProps are namespaced onto "s" in mapState().

推荐答案

看起来只有使用 mergeProps 才能有效地完成:

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);

mergeProps 的文档在这里:https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#mergeprops-stateprops-dispatchprops-ownprops--object

the documentation for mergeProps is here:https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#mergeprops-stateprops-dispatchprops-ownprops--object

这篇关于将自己的道具与状态道具分开命名空间是一种有用的模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 12:59