Dva first reading document learning

The data management scheme based on Redux saga is detailed in the article Redux saga of Redux Middleware



1. Data flow direction



Concept: data changes are usually triggered by user interaction or browser behavior. Use dispatch to initiate actions, and then change state through a series of changes


(1) synchronization: directly change the state through Reducer


(2) asynchrony: first trigger Effects, then flow to the Reducer, and then the Reducer finally changes the state




(1) State -- data State


State represents the state data of the Model, which is usually a JavaScript object


const app = dva();
console.log(app._store); //  state data at the top


(2) Action -- the only way to change the state


Action is a common js object and the only way to change the state. Call an action through dispatch to change the corresponding state data. Action must be customized with type and other parameters. To initiate an action, it must be called through dispatch.


* * Note: the dispatch is passed in through props after the component connectModel**


  type: 'add',


The object in the dispatch is an action


(3) dispatch function -- Method of implementing action


The dispatch function is a function used to trigger the action (implementation of action) object. Action is the only way to change the state, but action only describes this behavior. It really needs dispatch to trigger this behavior.


In the dva, after the component connects the Model, it can use props to access the dispatch, and then the dispatch can call the Effects in the Model and then call the Reducer or directly call the Reducer to change the state


  type: 'user/add',



(4) Reducer -- describe and implement data changes


The Reducer function accepts two parameters, the result of the operation that has been accumulated before and the value to be accumulated at present, and returns a new result (two parameters: current value and operation)


In Dva, the result of the first parameter aggregation accumulation is the state of the current model. The value passed in through action is calculated with the value in the current reducer to return a new state. Reducer must be a pure function. The same input and output values must be the same.


 reducers: {
        // reducer execution function
        'delete' ( state, { payload: id } ) { 
            // Return the value in the array state that is not equal to the incoming id. build a new array to delete the incoming id
            return state.filter(item => item.id !== id)




Action processor, which handles asynchronous actions, is implemented based on Redux saga. Effect refers to side effects. According to functional programming, operations other than calculation belong to effect, typically I/O operation and database reading and writing.


In order to control the operation of side effects, the bottom layer of dva introduces redux-sagas Do asynchronous process control, due to the use of Related concepts of generator Therefore, asynchronous is converted to synchronous writing, and effects is converted to pure functions.



   effects: {
      *fetchFront ( { payload }, { call, put } ) {
         const response = yield call( query, 'frontservice', { query: frontQuery, variables: payload.variables } );
         yield put({
        type: 'saveFront',
        payload: response.data,  


yield: identifies the operation of each step


call: execute asynchronous function


Put: issue Action, use put (similar to dispatch), operate reducer and change state





Subscription is a method of obtaining data from a source, which comes from elm


Subscription semantics is subscription, which is used to subscribe to a data source and then dispatch the required action s according to the corresponding conditions. The data source can be the current time, the websocket connection of the server, the keyboard input, the change of geography, the change of history route, and so on


import key from 'keymaster';
  namespace: 'count',
  subscriptions: {
    keyEvent({dispatch}) {
      key('⌘+up, ctrl+up', () => { dispatch({type:'add'}) });


(*) examples


The following is an example of a complete Model


export default {

  namespace: 'example',

  state: {},

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line

  effects: {
    *fetch({ payload }, { call, put }) {  // eslint-disable-line
      //Asynchronous operation
      yield call({delay,1000})
      //Issue Action
      yield put({ type: 'save' });

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };





The routing here refers to the front-end routing. In spa applications, the front-end code needs to control the routing logic and route related operations


import React from 'react';
import { Router, Route, Switch } from 'dva/router';
//Introduce component
import IndexPage from './routes/IndexPage';
import Products from './routes/Product'

function RouterConfig({ history }) {
  return (
    <Router history={history}>
        <Route path="/" exact component={ IndexPage } />
        <Route path="/products" exact component={ Products}/>

export default RouterConfig;


dva provides router to control routing, and uses react router


4,Router Components


In dva, the components that need to connect Model are usually Route Components, which are organized in the / routes / directory as page components;

Under the / components / directory, there are pure components, which are generally used as general components



  • roadhog


Document address: https://github.com/sorrycc/roadhog


Roadhog is a command-line tool including dev,build and test. Based on react dev utils, it can be understood as a configurable version of create react app.



  • propTypes


Use propTypes for type checking to verify and ensure that the props received by the component is a valid data type. When the incoming prop value type is incorrect, the JavaScript console will display a warning. For performance reasons, propTypes is only checked in development mode.

import React from "react";

import PropTypes from "prop-types";

// Pure function component writing method (pass in, delete and list array pros)
class ProductList extends React.Component{

// propTypes check
ProductList.propTypes = {
  //Check the data type and it is required
  onDelete: PropTypes.func.isRequired,
  products: PropTypes.array.isRequired

export default ProductList;




Tags: Javascript React

Posted by fugix on Tue, 03 May 2022 08:16:51 +0300