在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 }
本文介绍如何使用Redux Thunk中间件实现异步请求,并展示了如何创建异步action来处理数据加载、更新等操作。
1530

被折叠的 条评论
为什么被折叠?



