用法:
下载包进行安装,store主入口,hooks简化store(复制粘贴进去即可),slice相当于store中的模块化,最后在页面根入口导入store,并使用即可
1、安装
npm install @reduxjs/toolkit react-redux -D
2、目录结构
store.ts
import { configureStore } from '@reduxjs/toolkit'
import userSlice from './slice/userSlice';
import mySlice from './slice/mySlice';
export const store = configureStore({
reducer: {
userSlice,
mySlice
},
middleware:getDefaultMiddleware => getDefaultMiddleware({
//关闭redux序列化检测, 异步函数请求接口时,返回的对象无法序列化
serializableCheck:false
})
})
// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>
// 推断出类型: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch
hooks.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'
// 在整个应用程序中使用,而不是简单的 `useDispatch` 和 `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
slice.ts
import { PayloadAction, createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from 'axios';
const initialState:{
userId:string
} = {
userId:"1"
}
export const userSlice = createSlice({
name:"user",
initialState,
reducers:{
increment:(state,action:PayloadAction<string>)=>{
console.log(action)
state.userId = action.payload
}
},
extraReducers:(build)=>{
// 异步请求fulfilled后要做的事
build.addCase(getApiInfo.fulfilled,(state,action)=>{
state.userId = action.payload.data.data.id;
});
build.addCase(getApiInfo2.fulfilled,(state,action)=>{
state.userId = action.payload.data.data.id;
})
}
});
// 异步请求
export const getApiInfo = createAsyncThunk('getApi', async()=>{
const info = await axios('https://13123/111/22',{
method:'POST',
headers:{
"Sessionid":""
}
});
return info
});
export const getApiInfo2 = createAsyncThunk('bbbbbbbb', async()=>{
const info = await axios('https://13123/111/22',{
method:'POST',
headers:{
"Sessionid":""
}
});
return info
})
export const { increment } = userSlice.actions;
export default userSlice.reducer
index.tsx(页面入口处)
import { createRoot } from 'react-dom/client';
import RouterRender from './router/RouterRender';
import { RouterProvider } from 'react-router-dom';
import { Provider } from 'react-redux';
import { store } from '@/redux/store'
const root = createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<Provider store={store}>
<RouterProvider router={RouterRender}></RouterProvider>
</Provider>
);
完工