Today, I noticed that the company’s project uses DVA to build the project, so I thought about learning DVA. First of all, DVA is a data flow solution based on Redux and Redux-Saga. It also has react-Router and FETCH built-in, so it can also be understood as a lightweight application framework. In human terms, this is a lightweight package based on Redux, React-Saga and React-Router, with less than 100 lines of code, making every split action become a simple array object like vuex and other state management tools.

model

In DVA, the Model replaces most of the previous store and Reducer functions. In the original REDUx, data was uniformly stored in store and then processed by reducer, which were all placed in model in DVA. The following code

const model = {
    namespace:'product',
    state:[],
    reducers:{
        'delete'(state,{payload:id}){
            return ...
        }
    },
    setup({ dispatch, history }) {  
      window.onresize = () => {  
        dispatch (type:"save")  
      }
    },
}

export default model
Copy the code

In the code above:

  • namespaceRepresents a key on global state, which is used for separate naming purposes
  • stateIs the initial value and is equivalent to the store function in Redux
  • reducersSame as reducer in REdux, receive action and update state synchronously
  • effectIt is used to do asynchronous operations, sort of like action with middleware, which is a wrapper around Redux-Saga

So that’s what the properties of model do. Now we’re going to use model in our code.

  • subscriptionsaIt is used to subscribe to a data source and dispath an action based on the criteria. This is called a listener, as shown in the code above, which is an event that is triggered when the page is resized

conncet

Like react-redux, dVA has a connect method that connects components to the model and dispatches a method whenever an action needs to be published:

Function handleDelete(id) {dispatch({type: 'products/delete', payload: id,}); }Copy the code

The only thing left to do is initialize the data, which means receiving a bunch of requests and sending a bunch of responses, and finally get the code running.

Dva data flow

The data flow of DVA is one-way. Every time a user interacts on the page, we will initiate an action through Dispath and then perform the action. If it is synchronous operation, the value in State will be changed directly through reducers; if it is asynchronous operation, DVA will first trigger effects and then flow to Reducers and finally change State. This is a picture from the DVA website

The above is my general understanding of DVA