ful*_*ris 1 typescript reactjs redux redux-toolkit
官方Redux Toolkit 文档建议输入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
Run Code Online (Sandbox Code Playgroud)
但是,当将 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
Run Code Online (Sandbox Code Playgroud)
有人知道我如何协调保持配置存储调用函数(遵循 Gatsby 最佳实践),但仍然以某种方式获取类型(这样我就可以在整个应用程序中RootState使用类似的东西)?useSelector
坚持住你的帽子:
type ConfiguredStore = ReturnType<typeof store>;
type StoreGetState = ConfiguredStore["getState"];
export type RootState = ReturnType<StoreGetState>;
export type AppDispatch = ConfiguredStore["dispatch"];
Run Code Online (Sandbox Code Playgroud)
作为旁注,我建议命名该函数makeStore或类似的名称,而不是仅仅调用它store。
| 归档时间: |
|
| 查看次数: |
1090 次 |
| 最近记录: |