【问题标题】:Hooking up React Redux to a Component in Typescript将 React Redux 连接到 Typescript 中的组件
【发布时间】:2021-01-01 09:31:28
【问题描述】:

我希望在 typescript 中将 React Redux 连接到我的组件。我正在使用这些docs 作为模板。

我有以下类型来定义我在 Redux 存储中的状态(只有一个):

export interface rootState {
  favourites: ImageThumbnail[]
}
 

我的组件:

...

interface StateProps {
  favourites: NasaImageThumbnail[]
}

interface DispatchProps {
  addFavourite: () => void
  removeFavourite: () => void
}

interface OwnProps {
  ...
}

const mapState = (state: rootState) => ({
  favourites: state.favourites
})

const mapDispatch = {
  addFavourite: () => ({ type: 'ADD_FAVOURITE' }),
  removeFavourite: () => ({ type: 'REMOVE_FAVOURITE' })
}

type combinedProps = StateProps & DispatchProps & OwnProps

//Component body

export default connect<StateProps, DispatchProps, OwnProps>(
  mapState,
  mapDispatch
)(Component)

connect 函数中的 mapState 产生以下错误:

没有重载匹配这个调用。最后一个重载给出了以下 错误。 '(state: rootState) => { favourites: ImageThumbnail[]; 类型的参数}' 不可分配给类型参数 'MapStateToPropsParam'。 输入 '(state: rootState) => { favourites: ImageThumbnail[]; }' 不可分配给类型 'MapStateToPropsFactory'.

【问题讨论】:

    标签: typescript react-native redux react-redux


    【解决方案1】:

    不要将所有这些通用参数传递给connect。它们通常应该被推断出来。

    事实上,根据该页面,we specifically recommend using the ConnectedProps&lt;T&gt; technique to infer the type of props passed from connect to your component

    您还应该注意:

    【讨论】:

    • 对首选 redux 钩子的建议感到好奇。我是 React-Redux 的新手,但正在使用 redux-toolkit 开发一个大型项目。我对钩子最大的担忧是组件了解根状态形状,如果不更改每个组件中的选择器,我就无法重用它或重构我的代码。目前,我在创建状态切片后将组件连接到切片文件中,因此如果我确实更改状态,所有所需的连接更新都在一个地方。我的钩子关注的是组件的可重用性和耦合到状态形状。也许我的担心被误导了?
    • 这个问题是可以理解的,但不是一个严重的问题。无论您使用的是 connect + mapState 还是 useSelector,“选择器状态形状”问题都适用,因为 both 都将根 Redux 状态对象作为唯一参数。那里没有区别。如果您非常关心避免在组件中重写匿名选择器,请创建一个可在许多组件中调用的可重用选择器,这样您只需在状态形状发生变化时编辑缩减器和该选择器。
    • 有关此的更多详细信息,请参阅我的帖子 Using Reselect Selectors for Encapsulation and PerformanceThoughts on React Hooks, Redux, and Separation of ConcernsReactBoston 2019: Hooks, HOCs, and Tradeoffs。这也是使用 TypeScript 的一个很好的论据。
    • 哦,我会避免在切片文件中定义组件连接。绝对不是惯用的方法,而且我不记得见过其他人这样做过。
    • 切片文件中的连接是我做的,因为我不想将项目的其他部分导入到我的组件中(除了接口,我每个功能都保存在另一个文件中)。我的理由是,如果我在一个文件中定义状态切片,则连接的组件与状态相关联,那么我为什么要在组件文件中进行连接呢?看到组件文件底部的连接对我来说从来没有感觉很好,即使我确实看到了这样的例子。我完全是 redux-react 的菜鸟,感谢 Redux-Toolkit。
    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 2020-06-09
    • 1970-01-01
    • 2018-03-19
    • 2017-12-17
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    相关资源
    最近更新 更多