React Dva项目小优化之redux-action

之前 我们讲过 models
接下啦 我们来给大家讲一个新的库
这个库的话 有最好 没有影响也不大
它主要是帮助我们处理 action的
我们直接在 GitHub 官网上搜索 redux-action
在这里插入图片描述
我们搜出来 第一个就是 从星数来看 还是非常优秀的
在这里插入图片描述
我们拉下来 找到这个Documentation 然后点击进去
在这里插入图片描述
进入之后 拉下来 找到下面这个API 点击进去
在这里插入图片描述
第一件事 我们肯定是去安装这个依赖
终端执行

npm install --save redux-actions

在这里插入图片描述
它本身的API很少 只有三个
在这里插入图片描述
这里 我们也不一一介绍了
然后 我们在 src文件夹下创建一个文件夹 叫 actions 里面创建一个文件 叫 index.js

然后 我这里 根目录下 models 下有一个AsynchSchedul.js
代码是这样的

import * as api from "../services/example";

export default {
    
    

    namespace: 'AsynchSchedul',
  
    state: {
    
    },

    effects: {
    
    
        *getAsynchSchedulList({
     
      payload }, {
     
      call, put }) {
    
      // eslint-disable-line
            const dataList = yield call(api.getFilmData,payload);
            yield put({
    
    
                type: 'save',
                payload: dataList.data
            });
            return dataList.data
        },
    },
    subscriptions: {
    
    
        setup({
     
      dispatch, history }) {
    
    
            history.listen((location) =>{
    
    
                console.log(location);
            })
        },
        
    },
}

那么 正常情况
我们想在组件中使用这个getAsynchSchedulList函数
应该这样

this.props.dispatch({
    
    
   type: "AsynchSchedul/getAsynchSchedulList",
  payload: {
    
    
    id: 123
  }
}).then(res => {
    
    
  console.log(res);
})

但看着不是那么方便 我们可以将actions下的index.js改成这样

import {
    
     createAction } from "redux-actions";

export const getAsynchSchedulListApi = createAction("AsynchSchedul/getAsynchSchedulList");

就是定义一个变量名 接收这里面用createAction包一层地址 然后调用导出
之后 我们在要使用的地方这样写
在这里插入图片描述
引入是肯定要引入的
然后通过this.props.dispatch 里面直接放你包裹的函数去调用 如果有参数直接传给你包装的函数
例如 我这里的对象参数 直接就放在了getAsynchSchedulListApi中

这样 做一个小优化

老实说 这个东西给人的感觉有一点点画蛇添足 不要也罢

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/132225520