introduce

Dva is a data flow solution based on Redux and Redux-Saga. In order to simplify the development experience, DVA also has additional built-in React-Router and FETCH, so it can also be understood as a lightweight application framework.

The data flow

When users need to change data, they need to initiate an action through Dispatch. Synchronous operation will directly change State through Reducers; if it is asynchronous operation, Effects will be triggered first and then flow to Reducers and finally change State.

The characteristics of

  • Dva is divided into modules and has a namespace
  • Each module has a complete structure,state,reducer,effect
  • effectIs the part that handles asynchrony, used at the bottomredux-sagasDo asynchronous flow control
  • Data modification is required to passreducer

Dva – the use of the core

The installation

npm install dva-core
Copy the code

Dva – the core configuration

// dva.js DVa-core configuration file
import { create } from "dva-core";
// A collection of data modules that return an array
import models from "@/models";

// write the create function
function createApp(opts) {
    let app = create(opts);
    // To register the model, each must be registered
    models.forEach(model= > {
        app.model(model);
    })
    // Start the application after model registration and before store retrieval
    app.start();
    / / for the store
    const store = app._store;
    app.getStore = () = > store;
    app.dispatch = store.dispatch;
    return app;
}

const dva = createApp({});
export default dva.getStore();
Copy the code

Inject store into the project

  • To inject store into the project, usereact-reduxPlug-in injection
// Import file
import React from 'react'
import {Provider} from 'react-redux'
import App from './app'

// Import dVA configuration file, obtain store
import store from './dva.js'

const Index = () = > {
    return (
        <Provider store={store}>
            <App/>
        </Provider>)}Copy the code

Use in components

  • usereact-reduxIn theconnect, put store into the component
import React from 'react'
import {connect} from 'react-redux'

const Home = props= > {
    const {login} = props;
    
    return <h1>{login.name}</h1>
}

export default connect(store= > ({
    login: store.login // Inject the store of the login module into the project
}))(Home)

Copy the code