redux 学习四

本文介绍如何使用Redux Thunk中间件实现异步请求,并展示了如何创建异步action来处理数据加载、更新等操作。

在redux中异步请求怎么写

写在action文件夹中

下载中间件  npm i redux-thunk

在 store文件夹中引入

import { createStore, combineReducers, applyMiddleware } from "redux"
import thunk from "redux-thunk"

并且导出

export default createStore(store, applyMiddleware(thunk))

完整的

import { createStore, combineReducers, applyMiddleware } from "redux"
import thunk from "redux-thunk"
import userlistreducers from "../reducers/userlistreducers"
import flagreducers from "../reducers/flagreducers"
let store = combineReducers({
    userinfo: userlistreducers,
    flaginfo: flagreducers

})
export default createStore(store, applyMiddleware(thunk))

在action文件夹中写数据请求    dispatch触发同步操作 再改变全局数据

let asyncdel = (id: any) => {
    return async (dispatch: any) => {
        await userModel.del(id)
        dispatch(del(id))
    }
}

导出

export { asyncdel, asyncinitlist, asyncadd }

页面导入 这些异步方法 同时也操作了同步的方法

import { asyncdel, asyncinitlist, asyncadd } from "../action/useraction"

完整的

import actiontype from "./actiontype"
import userModel from "../model/userModel"


let initlist = (playload: any) => {
    return {
        type: actiontype.INIT,
        playload
    }
}


let del = (playload: any) => {
    return {
        type: actiontype.Delete,
        playload
    }
}

let add = (playload: any) => {
    return {
        type: actiontype.ADD,
        playload
    }
}


let asyncdel = (id: any) => {
    return async (dispatch: any) => {
        await userModel.del(id)
        dispatch(del(id))
    }
}

let asyncinitlist = () => {
    return async (dispatch: any) => {
        let { data: list } = await userModel.query({})
        dispatch(initlist(list))

    }
}

let asyncadd = (info: any) => {




    return async (dispatch: any) => {


        let { data } = await userModel.query({
            username: info.username
        })

        if (data.length) {
            if (info.error) {
                info.error("用户名已经存在")
            }


        } else {

            let { data: list2 } = await userModel.add({
                username: info.username,
                userpwd: info.userpwd
            })
            dispatch(add(list2))

            if (info.success) {
                info.success("增加成功")
            }

        }




    }
}
export { asyncdel, asyncinitlist, asyncadd }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值