Redux-toolkit异步请求两种方式

asyncSlice.ts

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { request } from '@/utils/http'

interface SimpleInfo {
    oraInfo?: [],
    depInfo?: []
}

const initialState: SimpleInfo = {
    oraInfo: [],
    depInfo: []
}

/**
 *  异步请求设置state方法1   payload:UI组件中dispatch(loadDep)传递过来的API地址
 * **/
export const loadDep = createAsyncThunk('simpleInfo/loadDep', (payload: any, thunkAPI) => {
    request(payload).then((res: any) => {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        thunkAPI.dispatch(setDep(res.data.data))
    })
})

/**
 * 异步请求设置state方法2  需额外添加extraReducers属性, loadOrg异步方法请求成功时,
 * 会自动执行[loadOrg.fulfilled],在里面直接修改state
 * (API地址也可在UI组件中dispatch时传递,参考实例1,用payload参数接收)
 * **/

export const loadOrg = createAsyncThunk('simpleInfo/loadOrg', () => {
    return request('/departments/simple').then((res: any) => res.data.data)
})

const { reducer: SimpleData, actions } = createSlice({
    name: 'simpleInfo',
    initialState,
    reducers: {
        setOrg(state, action) {
            state.oraInfo = action.payload
        },
        setDep(state, action) {
            state.depInfo = action.payload
        }
    },
    extraReducers: {
        // 成功fulfilled时执行的操作  pending等待  rejected拒绝
        // @ts-ignore
        [loadOrg.fulfilled](state: SimpleInfo, action: any) {
            state.oraInfo = action.payload
        }
    }
})

export const { setOrg, setDep } = actions
export default SimpleData

UI组件中使用:

import { loadDep } from '@/store/slice/asyncSlice'
import { loadOrg } from '@/store/slice/asyncSlice'

// 方式1
const httpClick = () => {
    // @ts-ignore
    dispatch(loadDep('/departments/simple'))
}

// 方式2
const httpClick1 = () => {
    dispatch(loadOrg())
}

你可能感兴趣的:(Umi&AntdPro,React,javascript,typescript,前端)