在 TypeScript 中键入 Redux 工具包的存储

Jea*_*hel 1 typescript reactjs redux

我正在尝试开始在 React + TypeScript 中使用 Redux,所以我正在关注 Redux Toolkit 的教程并尝试在示例应用程序中实现它。

我在打字时遇到了很多关于 store 和mappStateToProps函数参数的困难。

我用切片配置了商店,如下所示:

import { configureStore } from '@reduxjs/toolkit'

import linksReducer from '../features/links/linksSlice'

const store = configureStore({
  reducer: {
    links: linksReducer,
  },
})

export default store
export type AppStore = typeof store
Run Code Online (Sandbox Code Playgroud)

我像这样连接了一个组件:

import React from 'react'
import { connect, ConnectedProps } from 'react-redux'

import { AppStore } from '../../features/appStore'
import { deleteLink } from '../../features/links/linksSlice'

import LinkCard from './LinkCard'
import Link from '../../models/Link'
import EmptyList from './EmptyList'

const mapStateToProps = (state: any) => ({
  links: state.links,
})
const mapDispatchToProps = { deleteLink }
const connector = connect(mapStateToProps, mapDispatchToProps)

const LinksGrid = (props: ConnectedProps<typeof connector>) => {
  //  ...
}

export default connector(LinksGrid)
Run Code Online (Sandbox Code Playgroud)

如您所见,我将any类型用作mapStateToProps函数的第一个参数,因为我不知道应该如何键入它。使用any,我运行应用程序没有问题,所以我假设我只有打字问题。

RTK的官方文档只给出了一个使用combineReducers而不是的例子configureStore,它使用的TSReturnType<T>只能作用于函数,当然store变量不是函数所以它不起作用。
我还阅读了 Redux 和 React Redux 文档,但我仍然不知道该怎么做。

我确信这实际上很简单,但我在这里......谁能帮我打字?

谢谢 :)

mar*_*son 5

无论是终极版工具包高级教程,并与打字稿使用文档的页面告诉你如何正确地做到这一点。

首先,重要的不是商店的类型。它是store state的类型。

如果您combineReducers()自己使用,则可以将该类型定义为:

const rootReducer = combineReducers({
    first: firstReducer,
    second: secondReducer,
});

type RootState = ReturnType<typeof rootReducer>
Run Code Online (Sandbox Code Playgroud)

但是,由于您通过将切片缩减器传递给configureStorecombineReducers()内部调用)来使用速记设置表单,因此您可以通过检查返回类型来做同样的事情store.getState

const store = configureStore({
    reducer: {
        first: firstReducer,
        second: secondReducer,
    }

});

type RootState = ReturnType<typeof store.getState>
Run Code Online (Sandbox Code Playgroud)

然后,如文档中所示,您可以将RootState类型导入组件文件并将其用作mapState函数中的类型:

import {RootState} from "app/store";

const mapStateToProps = (state: RootState) => ({
  links: state.links,
})
Run Code Online (Sandbox Code Playgroud)