*Redux Toolkit 是官方推荐的编写 Redux 逻辑的方法**。
Redux Toolkit介绍
Redux Toolkit 是官方推荐的编写 Redux 逻辑的方法。
在前面我们日常react项目中使用Redux状态管理的时候应该已经发现,redux的编写逻辑过于的繁琐和麻烦。 并且代码通常分拆在多个文件中(虽然也可以放到一个文件管理,但是代码量过多,不利于管理); Redux Toolkit包旨在成为编写Redux逻辑的标准方式,从而解决上面提到的问题; 在很多地方为了称呼方便,也将之称为“RTK”
redux tookit官网
https://redux-toolkit.js.org/
安装Redux Toolkit
npm install @reduxjs/toolkit react-redux
redux/tookit常用API
configureStore: 包装createStore以提供简化的配置选项和良好的默认值。 它可以自动组合你的 slice reducer,添加你提供 的任何 Redux 中间件, redux-thunk默认包含,并启用 Redux DevTools Extension。 createSlice: 接受reducer函数的对象、切片名称和初始状态值,并自动生成切片reducer,并带有相应的actions。 createAsyncThunk: 接受一个动作类型字符串和一个返回承诺的函数,并生成一个pending/fulfilled/rejected基于该承诺分 派动作类型的 thunk
创建store文件
//引入tookit
import { configureStore } from '@reduxjs/toolkit'
//引入reducer slice
import { reducer } from './reducers/user'
//创建store
const store = configureStore({
//放置单独reducer切片 默认多合一
reducer: {
users: reducer
},
devTools: true
});
export default store;
创建slice切片
//引入reducer
import { createSlice } from '@reduxjs/toolkit'
//创建slice
const userSlice = createSlice({
name: "User", //切片名称
initialState: {
count: 0
},
//类似事件类型
reducers: {
increment(state, action) {
console.log(state, action);
let { payload } = action;
state.count += payload;
}
},
});
//导出对应的action
export const { increment } = userSlice.actions;
//导出当前的reducer
export const reducer = userSlice.reducer;
关联到react项目
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import { Provider } from 'react-redux'
import store from './store/index'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
)
组件中直接使用
import { useDispatch, useSelector } from "react-redux"
import { increment } from './store/reducers/user'
export default () => {
let state = useSelector(state => state);
let dispatch = useDispatch();
console.log(state);
let add = () => {
//触发动作
dispatch(increment(1));
}
return <>
<div>测试---{state.users.count}
<button onClick={add}>++</button>
</div>
</>
}
异步的thunk
创建异步的thunk
//引入reducer
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
//创建异步thunk
export let userLoginThunk = createAsyncThunk("fetchlogin", async (args) => {
let res = await 123;
return res;
});
//创建slice
const userSlice = createSlice({
name: "User",
initialState: {
count: 0
},
//类似事件类型
reducers: {
increment(state, action) {
console.log(state, action);
let { payload } = action;
state.count += payload;
}
},
//监听异步的结果
extraReducers: {
[userLoginThunk.fulfilled](state, action) {
let { payload } = action;
console.log(state, payload);
state.count = payload
}
}
});
//导出对应的action
export const { increment } = userSlice.actions;
//导出当前的reducer
export const reducer = userSlice.reducer;