1 安装
npm install @reduxjs/toolkit
2 创建store目录
创建store文件夹,里面包含入口文件index.jsx,以及自定义的reduces方法main.jsx的slices文件夹,其中main1.jsx、main2.jsx表示每一个相对独立的reduces数据操作集
store
***slices
******main1.jsx
******main2.jsx
******…
***index.jsx
3 定义store结构
index.jsx(在项目入口处引入该文件)
import { configureStore } from '@reduxjs/toolkit'
import main1 from './slices/main1'
import main2 from './slices/main2'export const store = configureStore({reducer: { main1, main2 }
})export default store
main1.jsx(在页面中引入该文件)
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'const initialState = {status: 10,
}export const getRequestFn = createAsyncThunk( // 异步接口修改state'requestName',async () => {try {// 触发一个请求const { data } = await requestApi()return data} catch (err) {console.log('requestName', err)}}
)const mainSlice = createSlice({name: 'main1',initialState,reducers: {increment(state, action) {state.status = state.status + action.payload},decrement(state, action) {state.status = state.status - action.payload},changeValue(state, action) {state.status = action.payload},},extraReducers(builder) {builder.addCase(getRequestFn.fulfilled, (state, actions) => {if (!actions.payload) returnstate.status = actions.payload.status // 赋值为请求的data.status})}
})export const actions = mainSlice.actionsexport default mainSlice.reducer
4 使用
在项目入口处引入store/index.jsx,
并在需使用store的组件中引入store/slices/main.jsx
项目中的具体使用如下:
import React, { memo } from 'react'
import { useSelector, useDispatch } from 'react-redux'
// 这里引入main1的地址,main1、main2按需引入
import { actions, getRequestFn } from '**/store/slices/main1'function Home() {const { status } = useSelector(state => state.main)const dispatch = useDispatch()const handleAdd = () => {dispatch(actions.increment(1)) // status => 11}const handleAssign = () => {dispatch(actions.changeValue(100)) // status => 100}const handleRequest = () => {dispatch(getRequestFn()) // status => request data.status} return <div><div onClick={handleAdd}></div><div onClick={handleAssign}></div><div onClick={handleRequest}></div></div>
}export default Home
Redux官网