【问题标题】:Type definitions for Redux (Toolkit) store with preloadedState带有 preloadedState 的 Redux (Toolkit) 存储的类型定义
【发布时间】:2021-05-24 16:16:54
【问题描述】:

我正在尝试使用类型化来配置具有预加载状态的 Redux 存储。

Redux Toolkit TypeScript quick start guide 有这个例子:

import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({
  reducer: {
    one: oneSlice.reducer,
    two: twoSlice.reducer
  }
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

不幸的是,在预加载状态下,它看起来更像这样:

export function initStore(preloadedState) {
  const store = configureStore({
    reducer: {
      one: oneSlice.reducer,
      two: twoSlice.reducer
    },
    preloadedState,
  })

  return store
}

我现在从哪里获得RootState 类型和AppDispatch 类型?

【问题讨论】:

    标签: reactjs typescript redux types redux-toolkit


    【解决方案1】:

    Reducer 的状态

    您可以根据 reducer 的参数类型推断您的状态类型。我们希望将reducer 值分离为单独的const,以便仅在reducer 上使用typeof

    const reducer = {
      one: oneSlice.reducer,
      two: twoSlice.reducer
    };
    

    您正在使用切片缩减器的对象而不是创建的函数combineReducers。 Redux 工具包导出了一个实用程序类型,我们可以使用它从 reducer 映射对象表示法推断状态。

    import { StateFromReducersMapObject } from "@reduxjs/toolkit";
    
    export type RootState = StateFromReducersMapObject<typeof reducer>
    

    返回类型

    我们也可以通过查看initStoreReturnType 来获得Store 的类型,然后通过查看商店的getState 方法中的ReturnType 来获得RootState。那将与示例最相似。同样的方法还允许我们获取AppDispatch 的类型。请注意,我们使用括号表示法而不是点表示法,因为我们的 Storetype,而不是 object

    type Store = ReturnType<typeof initStore>
    type RootState = ReturnType<Store['getState']>
    type AppDispatch = Store['dispatch']
    

    预加载状态类型

    reducerinitStore 分开的好处是,我们现在可以使用reducer 中的类型来为preloadedState 参数声明适当的类型,这是之前没有输入的。

    import { configureStore, Slice, StateFromReducersMapObject, PreloadedState } from "@reduxjs/toolkit";
    
    const reducer = {
      one: oneSlice.reducer,
      two: twoSlice.reducer
    };
    
    export type RootState = StateFromReducersMapObject<typeof reducer>
    
    export function initStore(preloadedState?: PreloadedState<RootState>) {
      return configureStore({
        reducer,
        preloadedState,
      });
    }
    
    type Store = ReturnType<typeof initStore>
    
    export type AppDispatch = Store['dispatch']
    

    Typescript Playground Link

    【讨论】:

    • 只想添加...太酷了!谢谢你的详细解释!
    • @linda-paiste 我尝试了您的解决方案,除了preloadedState 的类型DeepPartial&lt;RootState&gt; 与参数preloadedState 不兼容之外,一切都很好。您可以在您提供的 TS Playground 链接中看到错误。
    • @cadenzah 感谢您指出这一点! RTK 包已更改 - 正确的类型曾经是 DeepPartial,但现在需要使用特定的 PreloadedState 类型。
    猜你喜欢
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 2020-08-13
    • 2020-12-27
    • 2021-12-07
    • 1970-01-01
    • 2019-04-07
    • 2022-10-20
    相关资源
    最近更新 更多