Initial use and application logic analysis of lightweight frame DVA based on React+redux

Source: Internet
Author: User
Tags documentation


With the fire of react, the flux architecture followed fire, Redux was the leader in the library of flux architecture, and more and more developers used React+redux to develop applications.






Indeed, REACT+REDUX+WEBPACK+BABEL+ES6, this is a highly productive combination.



The one-way flow from the flux architecture makes the logic and data flow of applications controllable, and when the application logic becomes complex, its advantages become more obvious and the development becomes more efficient



But there are some problems in development, such as too many concepts, too loose files, and so on.



And in order to solve the asynchronous interaction problem, will refer to some middleware to deal with the store, it is more common to use thunk middleware +ASYSC or with saga, etc.






Figure for a middleware to process the store code



This is not DVA solve the biggest problem, DVA focus is the introduction of the concept of model, the previous pile of loose concepts and documents organized together, this is the key



React+redux+redux-saga, each new 1 components or add 1 new pages, add 3 files, sagas,reducers,action each corresponding 1 files, the time to write constantly switch, extremely troublesome, and after a lot of documents, File management is not very convenient



DVA is the solution to these problems.



First of all, I want to say a question, that is ... DVA the name ...



Well, initially I focused on the framework because of its name, and then the curious point went in, and then it was attracted by its elegance, no longer can not extricate themselves ...






And then it's configuration file called Roadhog






If you are a ower, then you already want to wait and see.



Why use DVA?



The following is a description of the official documentation:



easy to learn and easy to use: Only 6 APIs, especially friendly to redux users



Elm Concept : through reducers, effects and subscriptions organization model



support for Mobile and react-native: Cross-platform



support for HMR: Currently models based on BABEL-PLUGIN-DVA-HMR support for components, routes and HMR



load Model and route dynamically : Speed up access on demand



plug-in mechanism : for example, dva-loading can automatically handle loading state, do not write over and over again Showloading and hideloading



Perfect Grammar Analysis library Dva-ast: DVA-CLI based on this implementation of the intelligent creation model, router, etc.



support typescript: through D.ts



Let ' s start!



First of all, DVA official document address, is posted on the github: DVA



The first is to install:



Use NPM Installation: NPM install Dva-cli@0.7-g



Note that: 1.node version must be above 6.5 2.dva-cli must be version in 0.7.x (can be installed after dva-cli with dva-v view version number)



The above two points are DVA official requirements



Then use the new command to create a DVA application: DVA new Dva-demo






Patience waits for creation to complete






This is the tip of the application creation success



OK, now let's look at creating a good project ~



You can try it first: NPM run start






Run the results as shown



URL is: http://localhost:8000/#/?_k=gebc0m



Well, a strange URL.



But if you know anything about front-end routing or react-router, it's hashhistory.



If you are not accustomed to be modified to Browserhistory



In the Index.js file in the root directory



Modify Code






Then run to see the effect






URL is normal.



However, if the route is changed to Browserhistory, the back-end code needs to be matched.



Now let's look at the directory of the created project.






It's obvious to see that the code is in the SRC folder.



In addition, a index.html file has been delegated to the public folder.



Let's open it to see


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dva Demo</title>
  <link rel="stylesheet" href="/index.css" />
</head>
<body>

<div id="root"></div>

<script src="/index.js"></script>

</body>
</html>









Obviously, this is a html template file of a typical React application, which is similar to the index.html content generated in the application created with create-react-app scaffolding.

We hardly make code changes to this html, nor add html tags, css files, etc., the focus of the entire file is only two lines of code in the body

<div id = "root"> </ div>

This is the div tag that determines the id. The React components we write are all displayed in this div block.

<script src = "/ index.js"> </ script>

Finally all js files will be packaged into this Js file and loaded uniformly

Look at the js file again

The entry file for the entire program is the index.js file in the root directory



import dva from 'dva';
import { browserHistory } from 'dva/router';
import './index.css';


// 1. Initialize
const app = dva({
  history: browserHistory,
});
// 2. Plugins
// app.use({});

// 3. Model
app.model(require('./models/example'));

// 4. Router
app.router(require('./router'));

// 5. Start
app.start('#root');










The comments written by dva-cli generated the files for us.

Initialize, then load the plugin, then load the model, then load the route, and finally start the program

We use this process to clarify the file relationship

First analyze from step 4 routing

The load statement is: app.router (require ('./ router'));

It can be clearly seen that the router.js file in the same root directory is loaded.

We open the router.js file


import React from 'react';
import { Router, Route } from 'dva/router';
import IndexPage from './routes/IndexPage';

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

export default RouterConfig;










It can be clearly seen that the main structure is to configure react-router, intercept "/", and then render IndexPage

According to the import statement, find IndexPage.js under the routes directory



import React from 'react';
import { connect } from 'dva';
import styles from './IndexPage.css';

function IndexPage() {
  return (
    <div className={styles.normal}>
      <h1 className={styles.title}>Yay! Welcome to dva!</h1>
      <div className={styles.welcome} />
      <ul className={styles.list}>
        <li>To get started, edit <code>src/index.js</code> and save to reload.</li>
        <li><a href="https://github.com/dvajs/dva-docs/blob/master/v1/en-us/getting-started.md">Getting Started</a></li>
      </ul>
    </div>
  );
}

IndexPage.propTypes = {
};

export default connect()(IndexPage);
















Obviously, this is a React component, and it is a container-type component called in Redux, because the component is decorated by the high-order function connect during export so that it can get data from the Redux state tree

Because this is a very simple page, and does not import the components encapsulated in the Components directory. If the page is complex during actual development, the component will be encapsulated in the Component, and then the components in the Routes directory will be imported. And then import it into the routing file

example.js in the components directory

import React from 'react';

const Example = () => {
  return (
    <div>
      Example
    </div>
  );
};

Example.propTypes = {
};

export default Example;












Just 1 example file, without using it, it doesn't make much sense

Let's go back to index.js in the root directory. We have traced back the files loaded in the routing part of step 4. Let's look at step 3

app.model (require ('./ models / example'));

It can be seen that the example.js file in the models directory is loaded

Open to see its code

export default {

  namespace: 'example',

  state: {},

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

  effects: {
    *fetch({ payload }, { call, put }) {  // eslint-disable-line
      yield put({ type: 'save' });
    },
  },

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

};











The concept of model is the core of dva. You can see that the above code is mainly divided into several fields: namespace, state, subscriptions, effects, reducers

These fields, the description given in the official documentation is this:

namespace-corresponding key value of reducer when combined to rootReducer

state-the initialState corresponding to the reducer

subscription-new concept of elm@0.17, executed after dom ready

effects-corresponds to saga and simplifies use

reducers- still corresponds to the original reducer, the concept has not changed

Familiar with react, redux, redux-saga application architecture, seamless switching

It can be seen that the bunch of actions and reducers in redux is concentrated in the model. You don't have to switch over to write code. In one file, it is very convenient to organize the code and no longer need code everywhere

The files in the services directory serve the files in the models directory

For more, you can go to the official CURD user-managed demo

12 steps 30 minutes to complete the user-managed CURD application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.