背景:react中使用typescript,在引入redux之后很多状态定义有问题,记录下来(文章记录学习react-redux过程中的踩坑)。
1.useSelector时,state语法报错,类型为unknown,如下图
我的store状态设置的很简单,两个模块导出,只在state中定义了一个基础类型
在组件中使用useSelector取state中的值,然后报state类型未知
我在user的reducer中定义了state(下图),不知道为什么还会报类型未知,头疼
于是在网上一顿好找,找到一个好办法:TypedUseSelectorHook
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
type RootState = ReturnType<typeof store.getState>;
const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
export {useAppSelector}
组件中使用
const account = useAppSelector(state => state.user?.account);//不会飘红,撒花
接着使用redux,总不能在action中派发同步数据呀,来点异步试试吧,不是不打紧,一试吓一跳,useDispatch又飘红了
useDispatch传入异步action报错:类型“(dispatch: Dispatch) => Promise”的参数不能赋给类型“UnknownAction”的参数。报错详情见下图
一步一个错怎么搞,头大。接着查,往死里查!!!
终于,不费(九)吹(牛)灰(二)之(虎)力给我找到答案了。
还是要看官网啊!!!
官网链接: https://redux.js.org/tutorials/typescript-quick-start
官网上入门教程就写着要定义类型!!!我眼瞎看不见,活该踩坑。
大致思路就是
1.先定义所需要的类型并导出
import { configureStore } from '@reduxjs/toolkit'
// ...
export const store = configureStore({
reducer: {
posts: postsReducer,
comments: commentsReducer,
users: usersReducer
}
})
// Infer the `RootState`, `AppDispatch`, and `AppStore` 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
export type AppStore = typeof store
2.重新定义hooks
import { useDispatch, useSelector } from 'react-redux'
import type { AppDispatch, RootState } from './store'
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()
3.组件中使用
const dispatch = useAppDispatch();
dispatch(action||asyncAction)
//
const state= useAppSelector(state => state)