【发布时间】: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