Introduce the React

  • Facebook is an open source JavaScript library
  • React combines with the ecobank to form a MV* framework
  • The React features:
    • Declarative codingYou just declare what you do where, and you don’t care how you implement it, like those higher-order functions on the array prototype.Programmatic implementationYou need to express what is done where and how to do it in specific code, such as for loops.
    • Component-based coding
    • Efficient (efficient DOM Diff algorithm to minimize page redraw)
    • Unidirectional data flow
  • Ecology is introduced
    • React-Router (Vue-Router)
    • Redux (Vuex)
    • Axios
    • Babel
    • Webpack

React lifecycle

  • getDefaultProps
  • getInitialState
  • componentWillMount
  • Render (must)
  • componentDidMount
  • componentWillReceiveProps
  • shouldComponentUpdate (<— this.setState())
  • componentWillUpdate (<— this.forceUpdate())
  • componentDidUpdate
  • componentWillUnmount
import React, { Component } from 'react'; Class Child extends Component {// componentWillMount, Render, componentDidMount // componentDidMount Hook will only in the component calls a, the other called componentWillReceiveProps (newProps) {the console. The log ('will use newProps', newProps); } shouldComponentUpdate(newProps) {// accept newProps if returnedfalseConsole. log('should update', newProps);
		return newProps.value === 3 ? false : true;
	}

	componentWillUpdate(newProps) {
		console.log('will update', newProps);
	}

	componentWillMount() {
		console.log('will mount');
	}

	render() {
		console.log('render');
		return (
			<div>Child</div>
		);
	}

	componentDidMount() {
		console.log('did mount'); } componentDidUpdate(oldProps) {// If the oldProps is set to the value of state, console.log() {// If the oldProps is set to the value of state, console.log()'did update', oldProps); }}export default Child;
Copy the code

Project-dependent installation

  • axios
  • Antd (using less, you can modify your own theme. We can introduce ANTD. CSS because the less file is already compiled and packaged, but ANTD is actually styled using less!)
  • react-router-dom
  • redux
  • Less (Install less)
  • Less-loader (Need to expose webpack configuration: YARN eject)
  • Babel-plugin-import (load component code and styles on demand, for example if we import a Button component, we will import only the Button style file accordingly)

Configuration is less

// If the webpack configuration is exposed, edit webpack.config.js. // Restart the service after editing. // Remember: use is used from back to front.test: /\.less$/,
  use: [
    require.resolve('style-loader'),
    {
      loader: require.resolve('css-loader'),
      options: {
        importLoaders: 1
      }
    }, {
      loader: require.resolve('postcss-loader'),
      options: {
        ident: 'postcss',
        plugins: () => [
          require.resolve('postcss-flexbugs-fixes')
        ]
      }
    }, {
      loader: require.resolve('less-loader')}}],Copy the code

Configuration load on demand (install babel-plugin-import)

// Open the webpack.config.js file {test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: paths.appSrc,
  loader: require.resolve('babel-loader'),
  options: {
    customize: require.resolve(
      'babel-preset-react-app/webpack-overrides'), // Add the following configuration // Project packaging will only package the components and style plugins you introduced: [['import', {
        libraryName: "antd"// If yes is specified"css", then it will introduce"antd/lib/button/style/css"// When you change the theme color of the button, you cannot change it, because we change the theme by changing the less variable // and the CSS file is already compiled and packaged // style:"css"/ / as specifiedtrue, it will load"antd/lib/button/style"> < span style = "color: RGB (51, 51, 51);true,}]}},Copy the code

Modify Antd theme colors

{
  loader: require.resolve('less-loader'),
  options: {
    modules: false, modifyVars: {// Change the theme color of ANTD"@primary-color": "#f9c700"}}}Copy the code

Project Routing Configuration

  • The home page of the project and the login page are the same level of routes, so you need to think about the configuration in advance
  • Define a router.js file to place the tier 1 route
  • Get the routing configuration inside the component using this.props. Children
// router.js

<Router>
    <Route path='/login' component={Login} />
    <Route path='/admin' render={(props) =>
        <Admin>
            <Route path={`${props.match.path}/home`} component={Home} />
            <Route path={`${props.match.path}/ UI /buttons'} component={buttons} /> </Admin>} /> </Router> // admin.js (a layout for the Home page) Class Admin extends Component {render() {
        return (
            <Row className="container">
                <Col span={4} className="nav-left">
	                <NavLeft />
                </Col>
                <Col span={20} className="main">
                    <Header />
                    <Row className="content"> // Render Route {this.props. Children} </Row> <Footer /> </Col> </Row>); }}Copy the code

Mock data and interface request encapsulation

  • Easy Mock (Writing an interface online)
  • Mock (configure the data that needs to be returned by the interface)
  • Axios (Request interface)
// Encapsulate the interface request import axios from'axios';
import { Modal } from 'antd';

const baseURL = 'https://.... ';

class Axios {
    static ajax(options) {
        return new Promise((resolve. reject) => {
            axios({
                method: 'get',
                url: options.url,
                baseURL: baseURL,
                timeout: 5000,
                params: (options.data && options.data.params) || ' '
            }).then((response) => {
                if (response.status === '200') {
                    const res = response.data;
                    if (res.code === 0) {
                        resolve(res);
                    } else{modal. info({title:'tip', content: res.data.msg }); }}else{// Interface error reject(response.data); }})})}}Copy the code

Encapsulate the AXIOS request and configure the broker

A project created using create-react-app can configure proxy directly in package.json

"proxy": "http://xx.x.x.xx:port"// Server addressCopy the code

Custom axios

import axios from "axios";
import { Modal } from "antd"; Const service = axios. Create ({timeout: 10000}) / / request intercept service interceptors. Request. Use (config = > {the console. The log ("config", config);
    config.headers["Authorization"] = "token"; // Generally, a token is required for interface requestsreturn config;
}, error => {
    console.log("Request interception error", error);
    Promise.reject(error);
})

service.interceptors.response.use(response => {
    let { data, statusText, status } = response;
    returnParse (data) {statusText, status, data: json. parse(data) // If the data returned by the back end is JSON serialized data needs to be parsed}}, error => {modal. warning({title: error.response.status, content: error.response.statusText }) Promise.reject(error); })export default service;

Copy the code

How to request (you can encapsulate request methods, such as GET requests)

import service from '.. /utils/request';
import { Modal } from 'antd';

export function ApiGet(url, params) {
    return new Promise((resolve, reject) => {
    	service.get(url, params)
    	    .then(res => {
            	if (res.status === 200) {
                    Modal.success({
                        title: res.status,
                        content: "Request successful!"
                    });
                    resolve(res);
            	} else {
                    Modal.warning({
                    	title: res.status,
                    	content: res.statusText
                    });
                    reject(res);
            	}
            })
            .catch(err => {
                console.log("err", err)
                Modal.warning({
                    title: "Error",
                    content: "Request error!"
                })
                reject(err);
            });
    });
}
Copy the code

The call is simple

ApiGet("Interface").then(res => {
    console.log(res);
}, err => {

})
Copy the code