【问题标题】:Redux Toolkit with TypeScript - typing RootState with an SSR framework like GatsbyRedux Toolkit with TypeScript - 使用 Gatsby 等 SSR 框架输入 RootState
【发布时间】:2021-05-14 18:08:30
【问题描述】:

the official Redux Toolkit docs 建议输入RootState 如下:

import { configureStore } from '@reduxjs/toolkit'
// ...

export const store = configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer,
  },
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

但是,当将 Redux 与 Gatsby 等服务器端渲染 (SSR) 框架一起使用时,我需要将我的 configureStore 调用导出为可调用函数,因此我可以确保它只实例化一次:

import { configureStore } from '@reduxjs/toolkit'
// ...

// 'store' is recommended by the gatsby team to be a function,
// See https://github.com/gatsbyjs/gatsby/blob/master/examples/using-redux/wrap-with-provider.js
export const store = () => configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer,
  },
})

// TODO: won't work because store is not a const anymore, it is a function!
// Infer the `RootState` and `AppDispatch` types from the store itself
// export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
// export type AppDispatch = typeof store.dispatch

任何人都知道我如何协调保持配置存储调用函数(遵循 Gatsby 最佳实践),但仍然以某种方式输入 RootState(这样我就可以在整个应用程序中使用 useSelector 之类的东西)?

【问题讨论】:

    标签: reactjs typescript redux redux-toolkit


    【解决方案1】:

    抓住你的帽子看这个:

    type ConfiguredStore = ReturnType<typeof store>;
    type StoreGetState = ConfiguredStore["getState"];
    export type RootState = ReturnType<StoreGetState>;
    export type AppDispatch = ConfiguredStore["dispatch"];
    

    作为旁注,我建议将该函数命名为 makeStore 或类似名称,而不是仅将其命名为 store

    【讨论】:

    • 太棒了!有用!我已修改您的代码以导出应用程序中所需的两个导出,RootStateAppDispatch。我忘记了,为了完整起见,我们也应该包含 AppDispatch 类型,遵循 Redux Toolkit 的建议。
    猜你喜欢
    • 2021-08-23
    • 2022-11-12
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2022-01-26
    • 2018-02-15
    • 2021-09-21
    • 2020-03-29
    相关资源
    最近更新 更多