preface

This was my first stop in the front end, and my first time writing on the platform. After a brief understanding of the related syntax and principles of HTML, CSS and JS, I spent almost two months learning the React framework. At the beginning of learning React, I wanted to follow the MDN documents as before. However, after reading it, I gave up because reading the documents to learn React was too unfriendly for beginners. Later, I found a React study video on Bilibili. So I followed the video and began to learn. Little by little, I started to build the knowledge framework of React, and then I built a simple real-time chat website with the video. At this point, the React framework is an introduction. The purpose of this article is to summarize the achievements of learning React during this period and my understanding based on this simple template project.

Project related

Project introduction

The project is called Silicon Valley Zhipin, a reference to the React tutorial’s example project. This project is a single page application (SPA) separating the front and background, including front-end application and back-end application. The features of this project are:

  1. User registration and login
  2. Two user types: Big God/boss list
  3. Registration of user information
  4. Live chat

Technology selection

  1. Front end: React technology stack + ES6 + Webpack
  2. Back-end: Node + Express + mongodb + socketIO

Related technology Introduction

  • Front end:
    1. React: The front-end development mainly adopts the React technology stack. In addition to React itself, it also includes other content related to React technology stack, mainly including: Redux for state management, React-Router for route management, antD-Mobile for page beautification
    2. ES6: ECMAScript 6 is a version of the JS family. Since it is a specification for a programming language, it is self-evident.
    3. Webpack: A module wrapper for JavaScript applications, used for project management. Since the focus of the project is on React, I did not have a detailed understanding of the specific content of Webpack. I just used it directly.
  • The backend:
    1. Node.js: I think it’s fair to say that The creation of Node is epoch-making for front-end development. Before it was created, JS could only run on the browser side, acting as a appendage to HTML to give HTML pages nice action. Node takes JS out of the browser and allows it to run on the server just like Java.
    2. Express: a Node server framework used to build the entire back-end server platform.
    3. Mongodb: a non-relational database used to store the data required for the application.
    4. SocketIO: Provides a socket interface for applications to implement real-time data transmission, that is, real-time chat

A little about

Probably due to a release issue, the projects given in the tutorial simply don’t work, even though many of them have been discontinued for maintenance. As a result, the running through project spent a lot of time on potholes.

React Project related

Scaffolding construction project

  1. Install react scaffold globally

npm install -g create-react-app

  1. Use scaffolding to create and launch the React project

create-react-app hello-react

cd hello-react

npm start

antd-mobile

  1. Install ANTD-Mobile into your project

npm install –save antd-mobile

  1. Implement component packaging on demand
    • Downloading dependency Packages

    npm install –save-dev react-app-rewired customize-cra

    • Changing the reference mode
    /* package.json */
    "scripts": {-"start": "react-scripts start",
    +   "start": "react-app-rewired start",
    -   "build": "react-scripts build",
    +   "build": "react-app-rewired build",
    -   "test": "react-scripts test --env=jsdom",
    +   "test": "react-app-rewired test --env=jsdom",}Copy the code
    • Create config-overrides. Js in the project root directory
    module.exports = function override(config, env) {
      // do stuff with the webpack config...
      return config;
    };
    Copy the code
    • Download the plugin > NPM install –save-dev babel-plugin-import
    • To change the config – overrides. Js
    + const { override, fixBabelImports } = require('customize-cra');
    
    - module.exports = function override(config, env) {-// do stuff with the webpack config...
    -   returnconfig; -}; +module.exports = override(
    +   fixBabelImports('import', {
    +     libraryName: 'antd-mobile',
    +     style: 'css', +}), +);Copy the code
    • Changing the reference mode
    - import Button from 'antd-mobile/lib/button';
    + import { Button } from 'antd-mobile';
    Copy the code
  2. Implementing custom themes
    • Downloading dependency Packages

    npm install –save-dev less less-loader style-loader css-loader

    • Create an antd-theme.json file to save your custom theme
    {
      "@brand-primary": "#1cae82"."@brand-primary-tap": "#1DA57A"
      }
    Copy the code
    • Change the code in config-overrides. Js
    const { override, fixBabelImports, addLessLoader } = require('customize-cra');
    
    const theme = require('./antd-theme.json');
    
    module.exports = override(
      addLessLoader({
        javascriptEnabled: true.modifyVars: theme,
      }),
      fixBabelImports('import', {
        libraryName: 'antd-mobile'.libraryDirectory: 'es'.style: true}));Copy the code
    • Write.less files to define user-defined styles and refer to them in the entry JS file.

react-router

The React-Router is a tool used to switch between the current display. Different components are rendered on the same page depending on the path.

  1. The installation

npm install –save react-router-dom

  1. use
    • Introduce the HashRouter into the entry JS and wrap all routing components in HashRouter when the page is rendered
    • Import the Switch and Route to the parent component that requires Route switching
    • Introduce child components into parent components
    • Wrap each child component:
    <Route path="/routeName" component={component}\>
    Copy the code
    • Encapsulate all routing components using the Switch component
    <Switch>
    	<Route path="/routeName" component={component}\>
    <Switch/>
    Copy the code
    • Redirect indicates the Redirect of the route. That is, the root path is the routing component of the page rendering. You only need to specify to
    <Redirect to="pathname"/>
    Copy the code

redux

Redux is the state management tool in the React family. State is hosted through Redux. The React component pulls the state out of the Redux for display or modification as needed. State maintenance is particularly complex when some states need to be used by multiple components at the same time, so state management needs to be unified.

  1. Installation: You need to install three dependencies: redux(redux’s own dependencies), React-Redux (the React plugin library that simplifies redux in React), redux-Thunk (the redux asynchronous programming dependencies), Redux cannot program asynchronously by default) and a redux-Devtools-extension for debugging

npm install –save redux react-redux redux-thunk

npm install –save-dev redux-devtools-extension

  1. Use:

Create a redux folder containing four.js files to store code related to redux

  • store.js

The code in this file is fixed as follows:

import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import {composeWithDevTools} from 'redux-devtools-extension'
import reducers from './reducers'

export default createStore(
    reducers,
    composeWithDevTools(applyMiddleware(thunk))
)
Copy the code
  • reducer.js

This file holds the public state of the project and is updated based on the state stored by action and previous State. Then use combineReducers to merge and export all the states managed by this file. The code is as follows:

import {combineReducers} from 'redux'
const initXXX = {
    }
function xxx(state=initXXX, action) {
    switch(action.state) {
        default:
            return state
    }
}
export default combineReducers({
    xxx
})
Copy the code
  • action.js

This file contains the action that triggers the state change, indicating when the state change started. These actions are divided into synchronous actions and asynchronous actions.

  • action-type.js

This file contains all action types. 3. Import the route and Redux after the index.js file, component rendering part:

ReactDOM.render((
    <Provider store={store}>
        <HashRouter>
            <Switch>
                <Route path="/register" component={Register}/>
                <Route path="/login" component={Login}/>
                <Route component={Main}/>
            </Switch>
        </HashRouter>
    </Provider>
), document.getElementById('root'))
Copy the code

Components that interact with Redux need to be packaged into container components in advance:

import React, { Component } from 'react'
import {connect} from 'react-redux'

class conCom extends Component {
    render() {
        return (
            <div>React container component</div>)}}export default connect(
  // The redux-managed state used by this component
    state= > (),
    {
  // The action required by the component
    }
)(conCom)
Copy the code

After wrapping, the required state and the action to be distributed can be found in props.

  1. Redux workflowAs shown in the figure, the state saved in Redux is saved in Store. When you want to change the state, you dispatch an action and Reducers change the state based on the previous state and action, which can be called directly by the React component.

Cross-domain broker problem

For cross-domain proxy issues, the tutorial will add directly to the packege.json file:

	"proxy":"http://localhost:4000"   // Add the cross-domain proxy at the end of the file
Copy the code

However, due to version changes, doing so will result in an error when crossing the domain broker. The final solution is to install the HTTP-proxy-Middleware plug-in, then add the setupproxy.js file to the root of the file and configure the relevant cross-domain proxy:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  // ...
  app.use(
    '/test',
    createProxyMiddleware({
      target: 'http://localhost:8000'.changeOrigin: true,})); }Copy the code

Backend engineering related

The whole back-end development architecture is Express +mongodb+socketIO. Follow the official documents to write, most of the problems are not very big. The socketIO that has more problems is the socketIO. SocketIO needs to download dependency packages from both the client and server. The commands on both sides are

npm install –save socket.io

  • Server:
    1. Add to bin/ WWW file
    var http = require('http');
    
    var server = http.createServer(app);
    
    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);
    
    require('.. /socketIO/server_socket')(server)
    Copy the code
    1. Create server_socket.js file to hold socket-related code:
    module.exports = function (server) {
    const io = require('socket.io')(server ,{
        cors: {
            origin: 'http://localhost:3000'.methords: ['GET'.'POST']}})// Monitor the connection between client and server
    io.on('connection'.function (socket) {
    console.log('A client has connected to the server')
    
    // Bind the listener to receive messages sent by the client
    socket.on('sendMsg'.function (data) {
        console.log('The server received a message from the client', data)
        // Process the data
        data.name = data.name.toUpperCase()
        // The server sends a message to the client
        // socket.emit('receiveMsg', data)
        io.emit('receiveMsg', data)
        console.log('Server sends message to client', data)
      })
    })
    }	
    Copy the code
  • Client: Without further ado, just paste the code
import io from 'socket.io-client'

// Connect to the server and get the connection object to the server
const socket = io('ws://localhost:8000')
// Bind the listener to receive messages sent by the server
socket.on('receiveMsg'.function (data) {
  console.log('Client receives message from server', data)
})

// Send the message
socket.emit('sendMsg', {name: 'abc'})
console.log('Client sends message to server', {name: 'abc'})
Copy the code

Data processing link

In a practical application, what matters most is how data flows. In this project, the data flow path is shown in the figure

After the react component finishes rendering the first screen, it sends an Ajax request to the server. After receiving the request, the server queries the corresponding data from the database through Mongoose and returns the queried data to the client. When the client receives the data returned from the server, the store in Redux manages it.

Since the components that need to interact with redux are wrapped as container components, you can query the status and distribute the action by simply looking for specific parameters in the props. An action corresponds to a change in the redux state. The action is called in the React component, and the changed state is synchronized directly to the container component, corresponding to the change in the display data.

Write in the back

It took two months to finish the demo project. This project has gained a lot, the most important is to go through the react app design process. Although through the process, but also a simple entry. It’s not learning at all. We have a long way to go.