安装redux
、react-redux
、@reduxjs/toolkit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
import { configureStore } from '@reduxjs/toolkit';
import userSliceReducer from './userSlice';
const store = configureStore({ reducer: { user: userSliceReducer, }, });
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;
|
定义 useDispatch, useSelector hook 类型
1 2 3 4 5 6 7 8
|
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'; import type { RootState, AppDispatch } from './index';
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) => { 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);
|