Redux-action for small optimization of React Dva project

We talked about models before,
and now let’s talk about a new library.
If there is a good library, it doesn’t affect much.
It mainly helps us deal with actions.
We directly search for redux-action on the GitHub official website,
insert image description here
and we found the first one. One is that it is still very good from the point of view of the number of stars.
insert image description here
Let’s pull down to find this Documentation and click to enter.
insert image description here
After entering, pull down to find the following API and click to enter.
insert image description here
The first thing we must do is to install this dependency.
Terminal execution

npm install --save redux-actions

insert image description here
Its own API is rarely only three.
insert image description here
Here we will not introduce them one by one.
Then we create a folder called actions under the src folder and create a file called index.js in it.


Then I have an AsynchSchedul.js code under the models in the root directory here .

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);
            })
        },
        
    },
}

So normally
we want to use this getAsynchSchedulList function in the component,
it should be like this

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

But it doesn't look so convenient. We can change the index.js under actions to this

import {
    
     createAction } from "redux-actions";

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

It is to define a variable name to receive a layer of address in createAction and then call the export.
After that, we write in the place where we want to use.
insert image description here
The import must be imported
, and then directly put the function you wrapped in this.props.dispatch to call if there is The parameters are directly passed to the function you wrap.
For example, the object parameters here are directly placed in getAsynchSchedulListApi

Do a small optimization like this

To be honest, this thing feels a little superfluous.

Guess you like

Origin blog.csdn.net/weixin_45966674/article/details/132225520