The basics of the React project were covered in detail in part 1 of this tutorial. In part 2, we will continue to explain the React advanced part. Have not read [the first] students please read in my public number oh ~

Super comprehensive detailed one-stop tutorial! Build the React Project from scratch

Before we begin, let’s review the content of [previous] introduction:

1 create the React – APP

2 Thin Projects

2.1 Deleting a File

2.2 Simplifying code

2.3 Using Fragments to Remove Outer Labels of Components

3 Project directory structure

3.1 Introduce global common styles

3.2 support Sass/Less/Stylus

4 the routing

4.1 Page Construction

4.2 use the react – the router – the dom

4.3 Route Forwarding

5 Importing Components

5.1 Creating the Header Component

5.2 Importing the Header Component

5.3 Component Parameter Transfer

6 React Developer Tools Browser plug-in

In this [Part 2], continue to share the following content:

A sneak peek

7 Redux and related plug-ins

7.1 installation redux

7.2 install the react – story

7.3 installation redux – thunk

7.4 Installing the Browser Redux plug-in

7.5 create the store

7.6 Store decomposition of complex projects

7.7 Interconnecting react-Redux with store

7.8 Starting Redux DevTools

7.9 Using immutable for Installation

8 Mock. Js installation and use

9 Resolve cross-domain problems in local development

10 Other common tools

Bonus chapter: Integrating Ant Design

11.1 Installing Ant Design

11.2 Load on demand

11.3 Customizing Theme Colors

7 Redux and related plug-ins

For those of you who have done VUE development, vuex is known as Redux, the react-Redux tool is also known as immutable.

Redux is long enough to be shared in its own right. This share is limited in space. It only briefly introduces the installation and deployment process. If you do not understand something, you may skip it or consult the official documents.

7.1 installation redux

Perform:

npm install  redux --save
Copy the code

Installing redux alone is also possible, but more cumbersome. Updating store data in redux requires manual subscription. Another plug-in (React-Redux) can be used to improve development efficiency.

7.2 install the react – story

Perform:

npm install react-redux --save
Copy the code

React-redux allows data in a store to be mapped to the props of a component via the connect method, eliminating store subscriptions. Properties read from store in state are read by props instead.

Since store (section 7.5) is not covered, the use of React-Redux is covered in Section 7.6.

7.3 installation redux – thunk

Perform:

npm install redux-thunk --save
Copy the code

Redux-thunk allows the function function to be returned in the actionCreators. This allows you to centralize business logic (such as interface requests) in actionCreator. Js, making it easy to reuse and simplifying the main file of the component.

7.4 Installing the Browser Redux plug-in

To facilitate redux status tracking, you are advised to install the Chrome plug-in.

Do a scientific search for “Redux DevTools” in the Chrome app store and install it.

It cannot be used directly after installation and needs to be configured in the project code. Here’s the explanation.

7.5 create the store

After installing the various plug-ins above, store can be used to manage state data.

If the project is simple, with only one or two pages, you can create just one master store to manage the overall project. The directory structure is as follows:

├ ─ / SRC + | ├ ─ / store + | | ├ ─ actionCreators. Js + | | ├ ─ contants. Js < -- defining methods of constant + | | ├ ─ index. The js + | | └ ─ reducer. JsCopy the code

Here is an example of the code for each file:

src/store/actionCreators.js:

import * as constans from './constants'

export const getData = (data) => ({
  type: constans.SET_DATA,
  data
})
Copy the code

src/store/contants.js:

export const SET_DATA = 'SET_DATA'
Copy the code

src/store/index.js:

import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'Redux DevTools const composeEnhancers = typeof Window ==='object' &&
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose

const enhancer = composeEnhancers(
  applyMiddleware(thunk)
);

const store = createStore(
  reducer,
  enhancer
)

export default store
Copy the code

This is the core code of the Store, which supports Redux DevTools. At the same time, redux-Thunk was integrated with Redux’s applyMiddleware functionality to create the Store.

src/store/reducer.js:

import * as constants from './constants'// initial defaultState const defaultState = {myData: null}exportDefault (state = defaultState, action) => {// State cannot be directly modified because it is referenced. Otherwise, state changes cannot be detected. So you need to make a copy of it and change it, and then return the new state.let newState = Object.assign({}, state)
    switch(action.type) {
        case constants.SET_DATA:
            newState.myData = action.data
            return newState
        default:
            return state
    }
}
Copy the code

In the code above, we set up a myData in store. How best to solve the state modification problem is covered in section 7.8.

7.6 Store decomposition of complex projects

For projects with more pages, it can be very expensive to maintain data in a single store. Let’s share how to break the Store into its components.

In general, each component has its own store, and stores under SRC are used as the aggregate to integrate each component’s store.

Take header and login components as examples to create their own stores.

Header’s store directory structure is as follows:

| | ├ ─ / components | | | ├ ─ / header + | | | | ├ ─ / store + | | | | | ├ ─ actionCreators. Js + | | | | | ├ ─ contants. Js + | | | | | ├ ─ index. Js + | | | | | └ ─ reducer. JsCopy the code

The index.js code in the component store is as follows:

import reducer from './reducer'
import * as actionCreators from './actionCreators'
import * as constants from './constants'

export { reducer, actionCreators, constants}
Copy the code

The idea is to aggregate other files in the component Store as a unified outlet.

The contants.js code in the component store is as follows:

const ZONE = 'components/header/'

export const SET_DATA = ZONE + 'SET_DATA'
Copy the code

The ZONE is used to avoid having the same name as contants of other components.

In the same way, create a store under Login (no further details).

Then change the total store under project SRC to the following directory structure:

├ ─ / SRC | ├ ─ / store - | | ├ ─ actionCreators. Js < delete - - | | ├ ─ contants. Js < - delete | | ├ ─ index. The js | | └ ─ reducer. JsCopy the code

SRC /store/index.js

import { combineReducers } from 'redux'

import { reducer as loginReducer } from '.. /pages/login/store'
import { reducer as headerReducer } from '.. /components/header/store'

const reducer = combineReducers({
    login: loginReducer,
    header: headerReducer
})

export default reducer
Copy the code

The above code is used to import the login and header stores, then merge them together via combineReducers, and add a unique object key value to each.

The benefits are clear:

  1. Avoid store data contamination of each component
  2. Components maintain their own stores independently, reducing maintenance costs

This approach to store maintenance is highly recommended.

7.7 Interconnecting react-Redux with store

To make it easier for each component to use store instead of referring to store over and over again. Let’s interconnect react- Redux with Store.

Modify the SRC/index. Js:

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
+   import { Provider } from 'react-redux'
+   import store from './store'
    import './common/style/frame.styl'

+   const Apps = (
+       <Provider store={store}>
+           <App />
+       </Provider>
+   )

M   ReactDOM.render(Apps, document.getElementById('root'))
Copy the code

This code uses the React-Redux Provider to deliver the store to the entire App.

In components that need to use store, the connect method provided by React-Redux is used to wrap the component.

Login, for example, to modify the SRC/pages/login/index, js:

    import React, { Component } from 'react'
    import Header from '.. /.. /components/header'
+   import { connect } from 'react-redux'
+   import * as actionCreators from './store/actionCreators'
    import './login.styl'

    class Login extends Component {
        render() {
            return (
                <div className="P-login">
                    <Header />
                    <h1>Login page</h1>
+                   <p>login: myData = {this.props.myData}</p>
+                   <button onClick={()=> {this.props.getData('123456'<button onClick={this.gotohome.bind (this)}> </button> </div>)}gotoHome() {
            this.props.history.push('/home'}} + // To map data in store to props + const mapStateToProps = (state) => ({+ myData: state.getin (['login'.'myData']), }) + // Map store dispatchtoprops = (Dispatch) => ({+ getData(data) {+ const action = actionCreators.getData(data) + dispatch(action) + } + }) Mexport default connect(mapStateToProps, mapDispatchToProps)(Login)
Copy the code

The biggest change is that the last line of code is wrapped with the Connect method.

Then map both state and Dispatch in the store to the props of the component. This can be accessed directly through props, where changes in the data in the store directly change props to trigger a view update for the component.

After clicking the button, you can see that the myData displayed on the page has changed.

The following is a visual trace through Redux DevTools.

7.8 Starting Redux DevTools

After section 7.5 setup, section 7.4 Redux DevTools is available. Click on the icon in the upper right corner of the browser, and you can easily track the changes of data in the store in a panel that appears.

You can also start Redux DevTools from the debug toolbar:

The specific method of use is not described here.

7.9 Using immutable for Installation

In section 7.5, it is mentioned that state cannot be directly modified in store, because state is a reference type, and direct modification may result in undetected data changes.

A. immutable B. immutable C. immutable D. immutable Data created using IMMUTABLE data is immutable, and any modification to immutable data will return a new IMmutable data, without changing the original IMmutable data.

Immutable. Js provides many methods that make it easy to modify reference data of object or array types.

To install immutable and redux-immutable, run:

npm install immutable redux-immutable --save
Copy the code

Then modify the code:

src/store/reducer.js:

-   import { combineReducers } from 'redux'
+   import { combineReducers } from 'redux-immutable'. (abbreviated)Copy the code

CombineReducers is redux-immutable.

And then modify the SRC/pages/login/store/reducer. Js

    import * as constants from './constants'
+   import { fromJS } from 'immutable'

M   const defaultState = fromJS({
        myData: null
M   })

+   const getData = (state, action) => {
+       return state.set('myData', action.data)
+   }

    export default (state = defaultState, action) => {
        switch(action.type) {
            case constants.SET_DATA:
M               return getData(state, action)
            default:
                return state
        }
    }
Copy the code

The immutable intervention is to convert primitive JS types to immutable types using the fromJS method.

Since state is already immutable, you can use the IMmutable set method to modify the data and return a new state. The code is much simpler, do not need to manually through Object. Assign and other methods to copy and reprocess.

Code changes to the header component will not be described again.

There are many other ways to use immutable, as described in the official documentation:

Immutable – js. Making. IO/immutable – j…

8 Mock. Js installation and use

During development, mock. js is often used to intercept Ajax requests and return preconfigured data to make it easier for the front-end to debug the interface alone. This section shows you how to use mock. js in your React project.

Perform installation:

npm install mockjs --save
Copy the code

Create a new mock.js under SRC as follows:

import Mock from 'mockjs'

const domain = '/api/'Mock. Mock (domain +'getData'.function () {
    let result = {
      code: 200,
      message: 'OK',
      data: 'test'
    }
    return result
})
Copy the code

Then introduce mock.js in SRC /index.js:

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
    import { Provider } from 'react-redux'
    import store from './store'
+   import './mock'
    import './common/style/frame.styl'. (abbreviated)Copy the code

It’s so simple. This way, a request for/API /getData in your project will be intercepted by mock.js and will return the data that was written in mock.js.

9 Resolve cross-domain problems in local development

In the React development environment, port 3000 is enabled by default, and the back-end API service may run on port 80 on the native machine, causing cross-domain problems during Ajax requests. Reverse proxies can be implemented with the HTTP-proxy-middleware tool.

Perform installation:

npm install http-proxy-middleware --save-dev
Copy the code

Create setupproxy.js under SRC with the following code:

const proxy = require('http-proxy-middleware');
module.exports = function (app) {
    app.use(
        '^/api',
        proxy({
            target: 'http://localhost',
            changeOrigin: true}}))Copy the code

As long as the request address begins with “/ API “, then reverse proxy to http://localhost domain, cross domain problem solved! You can modify it according to actual requirements.

※ Note: after setting setupproxy. js, you must restart the project to take effect.

10 Other common tools

  1. Axios – Ajax request tool

[official website] github.com/axios/axios

[Installation command]

npm install axios --save
Copy the code
  1. Better – Scroll – page native scroll experience effect tool

[official website] ustbhuangyi. Making. IO/better – scro…

[Installation command]

npm install better-scroll --save
Copy the code
  1. React-transition-group-css3 animation composition tool

【 official website 】github.com/reactjs/rea…

[Installation command]

npm install react-transition-group --save
Copy the code
  1. React -loadable – Dynamic load component tool

[official website] www.npmjs.com/package/rea…

[Installation command]

yarn add react-loadable
Copy the code

Bonus chapter: Integrating Ant Design

Ant Design is a very useful front-end UI library that has been used in many projects.

[website]

ant.design/index-cn

Based on the previous chapters, this section integrates Create-React-app with Ant Design after eject.

Please go to my wechat official number to read more

11.1 Installing Ant Design

11.2 Load on demand

11.3 Customizing Theme Colors

Build a React Project from Scratch (Part 2)

Project making

All the project codes involved in this sharing have been uploaded to GitHub. Students who need them can download them by themselves:

Github.com/Yuezi32/rea…

React family shares here all end, welcome to wechat official account private message with me.

Please pay attention to my personal wechat official number and get the latest articles at any time.