不到断气不罢休 发表于 2025-1-4 19:47:48

[redux] ts声明useSelector和useDispatch

先安装
安装 | Redux 中文官网
npm install react-redux
npm install @reduxjs/toolkit 界说一个切片
import { createSlice } from '@reduxjs/toolkit';

const userSlice = createSlice({
name: 'user',
initialState: {
    name: 'lsm',
    age: 24,
},
reducers: {},
});
//注意这里写导出reducer, 如果你不写就得在index.ts导入的时候写
export default userSlice.reducer;
总仓库导入
import { configureStore } from '@reduxjs/toolkit';
import userSlice from './user';
import shopSlice from './shop';
const store = configureStore({
reducer: {
    user: userSlice,
    shop: shopSlice,
},
});
// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>;
export default store;
main.ts导入
https://i-blog.csdnimg.cn/direct/43c2926b22ed4979be3a992ba4548428.png
怎么利用?
如许就行,返回的是总state, 得拿一个出来,这个时候发现点的时候没有提示????怎么办
https://i-blog.csdnimg.cn/direct/f3695c58b5f14ec3902215410b4e6d84.png
其实,这2个是一个东西,结果是true,以是只要拿到state的范例就行
const userStore = useSelector((state) => {
    console.log(state == store.getState());//true
}); 以是在index.ts里趁便导出
// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>; 不想写泛型, 如许写也可行
const shopStore = useSelector<RootState>((state) => state.shop);
const userStore = useSelector((state: RootState) => state.user);
console.log(shopStore);
console.log(userStore); 这时候你会好奇了 
ReturnType是什么

你传一个函数的范例进去会自动推断出返回值的范例了
typeof 是获取函数的范例, ReturnType会根据函数的范例推断出它的返回值范例的值
当然, 你也可以先调用store.getState()获取返回值,再用typeof获取返回值的范例也可以,但如许太蠢了!!! 不敷优雅!
// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>;//如许也可const RootStateData = store.getState();export type RootStateDataType = typeof RootStateData;
但还是很麻烦,表面引入还得声明(state: RootState)
以是在导出的时候重写函数就行了
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: [redux] ts声明useSelector和useDispatch