环境
- "react-redux": "^9.1.2"
- "redux": "^5.0.1"
- "@reduxjs/toolkit": "^2.2.6"
什么是 redux toolkit?
它优化了Redux的以下痛点
- 配置 Redux 存储太复杂了
- 添加很多package才能让 Redux 发挥应有的作用
- 需要太多样板代码
现在成为了编写Redux逻辑的标准方式。 其实笔者以前用的mobx,当初就是觉得redux用起来太麻烦了,狗都不用。现在出了toolkit,我看看怎么事。
使用
先看目录,非常简单简洁。
1. 编写Reducer
app-reducer,用来存储一些app事宜,比如全局loading的显示隐藏,debug按钮的显示隐藏。
定义好State,方便后续逻辑查看调用。action入参格式固定为PayloadAction结构
export interface AppState {
isDebug: boolean
loading: {
name: string
show: boolean
}
}
export const AppSlice = createSlice({
name: "App",
initialState: {
isDebug: config.env !== Env.PRODUCTION,
loading: {
name: "loading",
show: false,
},
} as AppState,
reducers: {
setDebug: (state, action: PayloadAction<{ show: boolean }>) => {
state.isDebug = action.payload.show
},
setLoading: (state, action: PayloadAction<{ loading: boolean; name?: string }>) => {
const { loading, name } = action.payload
state.loading = {
name: name ?? "loading",
show: loading,
}
},
},
})
export const { setDebug, setLoading } = AppSlice.actions
export default AppSlice.reducer
2.初始化Store状态树
IStore单纯只是定义数据结构,方便逻辑调用,和下面的reducer:{}格式一一对应
import { configureStore } from "@reduxjs/toolkit"
import userReducer, { UserState } from "./reducer/user-reducer"
import appReducer, { AppState } from "./reducer/app-reducer"
export interface IStore {
app: AppState
user: UserState
}
export default configureStore({
reducer: {
app: appReducer,
user: userReducer,
},
})
3. 使用
3.1 在hook中使用
// 定义状态值
const isDebug = useSelector((state: IStore) => state.app.isDebug)
// 使用useDispatch钩子,调用reducer的方法
const dispatch = useDispatch()
dispatch(setDebug({ show: false }))
3.2 在其他地方使用
// 直接使用store树调用,简单粗暴
import store from "../../store/store"
...
store.dispatch(setDebug({ show: false }))
完毕~是不是非常简单,真香