Less-3 build react project development template

Time:2021-11-25

Less-3 build react project development template

Project address:https://github.com/ZengTianSh…

preface:

stayLess-1: build a set of scaffolds suitable for react and ES6 development,Lesson-2: the design idea of Redux,
We already have some basic knowledge of building projects with react, which is launchedBuild react project development templateIt’s for
In the actual project, there is a perfect system or mechanism to meet our actual development needs. For example, in lesson-2, although we have
To enable the project to run with a data state management machine like Redux, lesson-3 is the combination of react
React Redux is further encapsulated to make the development more refreshing and the project easier to iterate and maintain.

Let’s take a look at a case encapsulated in this project:

Less-3 build react project development template

Preface 2:

If you are not familiar with the following knowledge points, you can read what I wrote in the previous article firstLesson-2: the design idea of Redux

We also need some middleware

In the process of encapsulating the project, we also need some useful middleware to support our encapsulation.

1、combineReducers

combineReducersFunction is used to split the reducer function. We have multiple case entries in the reducer function
The action sends the data and returns the state. However, when the project is complex and there are a lot of data, it is processed in a reducer function
Multiple different pieces of data are messy:

const chatReducer = (state = defaultState, action = {}) => {
  switch (action.type) {
    case TYPE1:
      // ...
       return state;
    case TYPE2:
       // ...
     return state;
    case TYPE3:
       // ...
    return state;
       //...
    default: return state;
  }
};

YescombineReducersWe can write reducer as follows:

//  reducer.jsx
export const reducerData1 =  (state ={}, action={}) => {
    switch (action.type){
              case 'TYPE1':
              return {count:233};
        default: return state;
    }
};
Export const reducerdata2 = (state = {Name: 'Zeng Tiansheng'}, action = {}) = >{
    switch (action.type){
              case 'TYPE2':
              return {
                name:state.name,
                age:'233'
              };
        default: return state;
    }
};
// ...

Finally, bind to the store:

// store.jsx
import * as reducer from './reducer'
var store = createStore(
    combineReducers(reducer),
    applyMiddleware(thunk)
);
export default store;

The merged reducer saves the state data of each child reducer and combines them into one state object. For example, the data obtained by reducer.jsx above is:

state:{
  reducerData1:{
    count:233
  },
  reducerData2:{
    Name: 'Zeng Tiansheng',
    age:'233'
  }
}

2、applyMiddleware

The simple explanation is that the dispatch () method of the store can be wrapped, for example, the network processing mechanism of wrapping an asynchronous request for store. Dispatch ().

3、redux-thunk

Although applymiddleware allows store. Dispatch (action) to do more, the only parameter that dispatch can receive is an object (action),
How can we do more? Redux thunk has modified store. Dispatch (), so that dispatch can receive a function as a parameter. With a function as a parameter, it can do more
More functions.

// action.jsx
export const increase = () => {
  return {type: 'INCREASE'}
}

Bind action to component:

import  * as action from '../../Redux/action.jsx'

connect(mapStateToProps, action)(Index);

Note that action.jsx export is a function, and you can return action directly without dispatch (), thanks to Redux thunk
What you did for us.

We need better tools

1. Fetch network request plug-in

The fetch standard defines the processes that request, respond, and bind them. You may think that the network request does not have Ajax, so it’s better to encapsulate it yourself, or jQuery
Isn’t $. Ajax popular and easy to use. However, event based asynchronous request is still very inconvenient in multi task processing. The fetch API is designed based on promise,
The great advantage of this is that there is no need to use layers of callback when requesting data, and our data can be processed in a chain operation.
If it’s not very clear, you canClick this link to see
Combined with react:

// action.jax
import fetch from 'isomorphic-fetch'  
export const fetchData = (url ,data) => {
  //Sending it to reducer indicates that the network request is in progress
   dispatch({type:'GETDATA_STAR'})
   return dispatch =>{
     fetch(url,{
        mode: 'cors',
        "Content-Type": "application/json"
     })
      .then(function(response) {
          if (response.status >= 400) {
              throw new Error("Bad response from server");
          }
          return response.json();
      })
      .then(function(data){
          //Finally, the obtained data is sent to the reducer, indicating that the data request is successful and the data is returned
           return dispatch({type:"GETDATA_END",data:data}});
      })
      .catch(function(error) {
          console.log('Request failed', error)
      });
   }
}

2. Immutable.js optimizes react performance

Immutable means immutable. We all know that once the state of react or the props data of the subcomponent changes, the component will be triggered to re render,
If the changed props has nothing to do with other components, but other components will also be affected and forced to render again, it will consume performance.
Immutable.js is to convert ordinary JS objects and arrays into immutable map and list collections. Make a deep comparison of JS data. If there is no change, it will be saved
Do not render components. Here is just a concept that can be used in large react projects. Please refer to Google for details

How to encapsulate our react project

There are a lot ahead. It depends on how it is encapsulated and applied in the project, otherwise it will be too abstract.
First look at the structure diagram of the project:

Less-3 build react project development template

Compared with lesson-2, we extracted action reducer and store separately and added a router component
There is also a template. Jax, which is used as a template for all components. You can see the sketch below to understand the location of each file
Role in the project:

Less-3 build react project development template

There are also good notes in the project, which can clone the project for operation analysis

clone [email protected]:ZengTianShengZ/react-lesson.git
cd lesson-3
npm install
npm run hot
Browser open: http://127.0.0.1:8088/

Summary:

Lesson-3 mainly continues the content of lesson-2 and encapsulates the react project combined with react Redux to make react
The actual project development is more refreshing and the project is easier to maintain. Some new knowledge points, such as combinereducers and Redux thunk, are also introduced
Middleware and easy-to-use network request fetch tools.

So far, the construction trilogy of react project has come to an end. If there are deficiencies, please issue. Welcomestar
I am also continuing to study hard and will make this project more perfect. Thank you!

Project address:https://github.com/ZengTianSh…