React@16.x(62)Redux@4.x(11)- 中间件2 - redux-thunk

目录

1,介绍

一般情况下,action 是一个平面对象,并会通过纯函数来创建。

js 复制代码
export const createAddUserAction = (user) => ({
    type: ADD_USER,
    payload: user,
});

这样是有一些限制的

  • 无法使用异步的,比如在请求接口之后再做一些操作。
  • 或根据条件,同时 dispatch 多个 action

redex-thunk 中间件的作用:允许 action 是一个函数,而不是一个平面对象。

举例

React@4.x 版本使用 redux-thunk@2.4.2 版本。

js 复制代码
export const createAddUserAction = (user) => ({
    type: ADD_USER,
    payload: user,
});

export const createSetLoadingAction = (isLoading) => ({
    type: SET_LOADING,
    payload: isLoading,
});

export const fetchUsers = () => {
    return async (dispatch) => {
        dispatch(createSetLoadingAction(true))
        const res = await getAllUsers();
        dispatch(createAddUserAction(res))
        dispatch(createSetLoadingAction(false))
    }
}
js 复制代码
// 使用
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { fetchUsers } from "./action/userAction";

const store = createStore(reducer, applyMiddleware(thunk));
store.dispatch(fetchUsers())

这个函数有3个参数:

  1. dispatch,就是 store.dispatch
  2. getState,就是 store.getState
  3. extra,设置的额外的参数。

2,原理和实现

整体流程:

实现

中间件的写法参考 这篇文章

js 复制代码
function thunkMiddleware(extra) {
    return (store) => (next) => (action) => {
        if (typeof action === "function") {
            return action(store.dispatch, store.getState, extra);
        }
        return next(action);
    };
}

const thunk = thunkMiddleware({});
thunk.withExtraArgument = thunkMiddleware;
export default thunk;

3,注意点

因为 redux-thunk 会修改 action 的类型,所以书写顺序通常会作为第一个。


以上。

相关推荐
海鸥两三17 小时前
uniapp 小程序引入 uview plus 框架,获得精美的UI框架
前端·vue.js·ui·小程序·uni-app
lightgis18 小时前
16openlayers加载COG(云优化Geotiff)
前端·javascript·html·html5
小飞大王66619 小时前
TypeScript核心类型系统完全指南
前端·javascript·typescript
你的人类朋友20 小时前
✍️记录自己的git分支管理实践
前端·git·后端
合作小小程序员小小店21 小时前
web网页开发,在线考勤管理系统,基于Idea,html,css,vue,java,springboot,mysql
java·前端·vue.js·后端·intellij-idea·springboot
防火墙在线21 小时前
前后端通信加解密(Web Crypto API )
前端·vue.js·网络协议·node.js·express
Jacky-00821 小时前
Node + vite + React 创建项目
前端·react.js·前端框架
CoderYanger1 天前
前端基础——CSS练习项目:百度热榜实现
开发语言·前端·css·百度·html·1024程序员节
i_am_a_div_日积月累_1 天前
10个css更新
前端·css
她是太阳,好耀眼i1 天前
Nvm 实现vue版本切换
javascript·vue.js·ecmascript