“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 10 天,点击查看活动详情”
1. 简介
- 昨天学习了Redux, 发现数据多了之后使用起来过于复杂,笨重,今天学习的Redux Toolkit就是为了解决这个问题。
- Redux Toolkit 是 Redux 官方强烈推荐,开箱即用的一个高效的 Redux 开发工具集,处理Redux中开发的重复性工作,简化Redux的流程。
2. 代码学习
- 安装
pnpm install react-redux @reduxjs/toolkit
- 存在多个Reducer时不需要合并了,直接使用进行配置
import {configureStore} from '@reduxjs/toolkit'
const store = configureStore({
reducer: {
user: userStore,
job: jonStore
}
})
- 使用Redux Toolkit时也不需要再创建legacy_createStore了
- 查询数据和Redux是一样的没有改版
- 使用新的hook帮我们创建action createAction
- create Action之后返回的是一个方法
const setUserName = createAction('setUserName')- 使用这个方法
<button onClick={() => dispatch(setUserName("王武"))}>修改名称</button> - 再次优化
- 在store文件中引入新的hook
import {createReducer} from '@reduxjs/toolkit'- 优化store
这样优化的话需要把createAction也放到store文件中,在使用的时候再进行导出,这不是一个好的优化方法
export const setJobNam = createAction('setJobNam') const jonStore = createReducer({ name: '程序员', total: 10 }, builder => { builder.addCase(setJobNam, (state, action) => { state.name = action.payload }) })<button onClick={() => dispatch(setJobNam("IT水泥工"))}>修改Jon</button>- builder.addCase 中需要一个Action方法,和一个回调函数,回调函数与昨天写的action是一样的
- 优化之后再简化 createSlice
createSlice 是一个全自动创建Reducer的方法,自动帮助我们进行调用createAction和createReducer
- 修改 store 文件
const foodStore = createSlice({
name: 'food',
initialState: {
name: '米饭',
weight: '1碗'
},
reducers: {
setName(state, action) {
state.name = action.payload
}
}
})
- 组合配置也与以往不同
const store = configureStore({
reducer: {
user: userStore,
job: jonStore,
food: foodStore.reducer
}
})
- 使用action动作修改数据, 需要导入reducer获取到全部 action
const {setName} = foodStore.actions
- 使用action
<button onClick={() => dispatch(setName("炸鸡"))}>修改foodName</button>
3. 总结
- 使用Redux Toolkit 之后,使用这个库给我们创建Reducer
- 不再需要使用合并Reducer,直接进行configureStore配置,自动帮我们进行合并
- 最终使用createSlice进行管理和更新store