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

Source: Internet
Author: User
Tags documentation html tags

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>

Obviously, this is an HTML template file that react typical applications, and is similar to the index.html content generated in applications created with Create-react-app scaffolding

We are almost no code changes to this HTML, and do not add HTML tags, css files, and so on, the focus of the entire file is only the body of two lines of code

<div id= "Root" ></div>

This is the DIV tag that identifies the ID, and the React component we write is finally displayed in this div block.

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

Finally, all JS files will be packaged into this JS file unified loading

Look at the JS file again

The entry file for the entire program is the Index.js file under 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 ');

Dva-cli generated files to our notes have been written very clearly

First initialize, then load the plug-in, then load model, then load the route, finally start the program

We're going to make it clear from this process that the file relationship

First, the 4th step is to analyze

The statement that loads the route is: App.router (Require ('./router '));

It's obvious that the Router.js file is loaded with the same root directory.

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 is obvious that the main structure is to configure React-router, intercept "/", and then render the Indexpage

According to the import statement, locate the 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}>
      

Obviously, this is a react component, and it is a container-type component in Redux, because it is decorated with the higher-order function of connect at the time of export so that the data can be obtained from the Redux state tree

Because this is a very simple page and does not import the packaged components in the components directory, if it is in actual development, the page is complex enough to encapsulate the components in the component, then import the components in the routes directory and import them into the routing file

The Example.js in the components catalogue

Import react from ' react ';

Const Example = () => {return
  (
    <div>
      Example
    </div>
  );

Example.proptypes = {
};

Export default Example;

Just 1 sample files, not using it, and it doesn't make sense in itself.

We go back to the root directory in the Index.js, the 4th-step routing part of the loaded files we have traced the end, we look at the 3rd step model

App.model (Require ('./models/example '));

As you can see, the Example.js file in the models directory is loaded

Open view its code

Export Default {

  namespace: ' Example ', state

  : {},

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

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

  reducers: {
    Save (State, action) { Return
      {... state, ... action.payload};},}
    ,}

;

Model This concept, is the core of DVA, you can see the above code is mainly divided into several fields: Namespace,state,subscriptions,effects,reducers

These are the fields that are described in the official documentation:

namespace-the key value corresponding to the reducer at combine to Rootreducer

State-corresponds to the reducer initialstate

New concept of subscription-elm@0.17, performing after Dom ready

Effects-corresponds to Saga and simplifies the use of

reducers-or corresponding to the original reducer, the concept has not changed

Familiar with React,redux, Redux-saga this set of application architecture, seamless switching

Can see, about redux in the action,reducer of that pile, are concentrated in model inside, write code no longer switch past switch over, and in a file, the organization code is very convenient, no code everywhere

The files under the Services directory are for files that are in the models directory.

More, you can go to see the official given a curd user management demo

12 Steps 30 minutes to complete the curd application of user management

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.