redux+ts

安装reduxreact-redux@reduxjs/toolkit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// store/index.ts

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

import userSliceReducer from './userSlice';

const store = configureStore({
reducer: {
user: userSliceReducer,
},
});

// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>;
// 推断出类型: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

export default store;

定义 useDispatch, useSelector hook 类型

1
2
3
4
5
6
7
8
// store/hooks.ts

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './index';

// 在整个应用程序中使用,而不是简单的 `useDispatch` 和 `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

创建一个 reducer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { createSlice } from '@reduxjs/toolkit';
import { RootState, AppDispatch } from './index';

const userSlice = createSlice({
name: 'user',
initialState: {
value: 123,
},
reducers: {
incremented: (state) => {
// Redux Toolkit 允许在 reducers 中编写 "mutating" 逻辑。
// 它实际上并没有改变 state,因为使用的是 Immer 库,检测到“草稿 state”的变化并产生一个全新的
// 基于这些更改的不可变的 state。
state.value += 1;
},
decremented: (state) => {
state.value -= 1;
},
},
});

export const { incremented, decremented } = userSlice.actions;

export const selectCount = (state: RootState) => state.user.value;

export default userSlice.reducer;

组件使用

1
2
3
4
import { useAppSelector, useAppDispatch } from '@/store/hooks';

const count = useAppSelector((state) => state.user.value);
console.log('count: ', count);
Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×