1. Create the React project

  • Install NPX create-react-app my_app
  • Run the NPM start

2. Environment Introduction

  • Node_modules depend on the package
  • Public entry file
  • SRC source code file
  • Package. json configuration file

These are very similar to uniApp or Vue structures

3. React and Vue file structures

  • React and Vue file structures are different
  • Vue: Structure is (template — logic — style)
<template>
	<view>The template</view>
</template>
<script>
	export default {
		data() {
			return {info:"Logic"}}}</script>
<style lang="scss" scoped>The view style of {}</style>
Copy the code
  • React: The JSX file contains logic and templates. React requires additional styling
import React, { Component } from 'react';
import "./myStyle.css";
export default class test extends Component {
    render() {
        return (
            <div>
            </div>); }}Copy the code

React — JSX syntax

JSX syntax is JS plus XML, interpretation is also very simple, encounter < > as HTML, encounter {} as JS

  • JSX syntax is especially detailed when traversing renderings
 <ul>
      {/* JSX () {/* JSX () {/* JSX () {/* JSX () {/* JSX ()}
      {
          this.props.myNav.map((e,i) = >{
          return <li key={i}>{e}</li>
          })
      }
  </ul>
Copy the code

JSX parses code by identifier

  • JSX syntax is unable to use HTML comments, want to use annotations can be {/ * * /} braces set it up, JSX resolution to the curly braces is automatically parsed into js syntax

React — Components

Super small knowledge

React constructor’s super() function, which initializes this, can bind events to this. If you use constructor but do not write super(), an error will be reported if you use this. If you do not write react, an empty constructor will be added with super().

React component names cannot start with a lowercase letter, but must start with a uppercase letter. Otherwise, a warning is displayed and no display is displayed

Warning: The tag <setStateDome> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
Copy the code

End suffixes can be JS component files, can also JSX end, in some idea JSX will also provide more grammar tips, a React project is composed of many components, it is in the front of the now modular development, ubiquitous vue or what is the abstract components, the code reusability is also stronger.

  • Components are introduced in much the same way as those in Vue, using ES6’s import, and imported components are presented as tags.
import Nav from './Nav/Nav';

// Create components as classes, or as hooks
export default class App extends React.Component{
    //render render function
    render(){
        const nav1 = ['home'.'learning'.'navigation']
        const nav2 = ['eat'.'sleep'.'Big Bubble']
        const { count } = this.state // What data is required and what data is introduced
        return ( 
            <>
            	<div>Welcome to components</div>/* Data can be transferred to child components by defining attributes. Since it is a function body, input variables directly. Custom attributes can transfer any type of data */<Nav myNav={nav1} title="This is a string." />
                <Nav myNav={nav2} />* /}<State />
            </>)}}Copy the code

A tip is to use deconstructed assignment when rendering the DOM, which saves a lot of code

6. React uses component local styles

  • React is not like Vue, which adds scoped to styles so that they don’t pollute globally
  • React’s solution is to introduce a file with the *.module. CSS suffix
    • So the class selector was.main, and when you use it, you just say className=”header”. But in component-local styles, you write className={styles.header} on the element that you want to specify the style.
// js
import React, { Component } from 'react';
import "./myStyle.css";				// The previous direct import method
import myStyle from "./myStyle.module.css";    // Reference styles in a named manner that does not pollute the environment
export default class componentName extends Component {
    render() {
        return (
            <>
                <div className={myStyle.main}></div>
            </>)}}// ./myStyle.module.css
.main{
    background-color: pink;
    width: 150px;
    height: 150px;
}
Copy the code

The first is imported directly, and the second is imported using local components.

Component imports are compiled into separate style names that are not overwritten. Global styles are overridden

7. Component communication mode

7.1, props is the only way that a parent component interacts with its children
  • The props feature cannot be modified, it can only receive and transfer data!

TypeError: Attribute title cannot be added, object is not extensible

## ./Nav/Nav.jsx
export default class Nav extends React.Component{
    render(){
        console.log(this.props.title)
        // When receiving data, we need to obtain it in props
        return (
            <div>
                <h3>{this.props.title}</h3>
                <ul>} {this.props. Mynav. map((e, I)=>{return */} {this.props. MyNav<li key={i}>{e}</li>})}</ul>
            </div>)}}Copy the code
7.2 Parent Components pass values to child components
  • In the tag that uses a subcomponent, add a custom property to pass data to the subcomponent. In the subcomponent, use this. Props
/ / the parent component
 <myChild myData={"Data passed by parent component"} / >/ / child component
 render() {
      console.log(this.props.myData)
  }
Copy the code
  • The child passes data to the parent, calls the parent by the child, and can return data as arguments
/ / the parent component
 render() {
      return (
          <div className="main">{/ *<Login/>* /}<myChild callback={this.childValue}/>
          </div>
      )
  }
  childValue = (data) = >{
      console.log('app',data)
      this.setState({
          dataList:data
      })
  }
 
/ / child component
  handleClick(){
      this.props.callback(this.state.count)
  }
Copy the code
7.3 Form Controls
  • React controls require an onChange binding method
constructor(){
    super(a);this.state={
        value:' '
    }
}
onChangeValue=(e) = >{
    this.setState({
        value:e.target.value
    })
}
render(){
	return <input type="text" value={this.state.value} onChange={this.onChangeValue}/>
}
Copy the code
  • Non-control unit

Refs can manipulate nodes on the DOM or element nodes created in the Render method,

  • Ref applies to these cases
    • Manage focus, text selection or media playback
    • Trigger forced animation
    • Integrate third-party DOM libraries
  • Refs need to be created using React.createrefs () and attached to the React element via the ref attribute. Do not overuse refs.

DOM manipulation is reserved for special cases

A ref can retrieve a bound DOM node and manipulate it, such as retrieving data or modifying styles.

constructor(){
    super(a);this.input = React.createRef();//
}
componentDidMount() {
    this.input.current.style.color='pink'// Modify the style of the DOM node
}
handleSubmit=(e) = >{
    alert('Test it out'+this.input.current.value) // Get the DOM node value
    e.preventDefault();// Cancel triggering the default behavior
}
render() {
    return (
       <input type="text" ref={this.input}/>
       <input type="submit" value="submit" onClick={this.handleSubmit}/>)}Copy the code

8. Event handling

8.1 this problem
  • The React function methods are different from those used in Vue. The function this in React refers to undefined. If you pass a function name to a variable and then call the method by enclosing parentheses () after the variable, the reference to this inside the method will be lost.
    • You can use the arrow function to give it access to the external context
    • You can bind external this to the function using bind(this)
    
    
    class componentName extends Component {
      constructor(props){
          super(props);
          // Bind in the constructor
          this.handleClick.bind(this)}// Use the arrow function to access the external context
      decrement=() = >{
          this.setState({
              count:this.state.count-=1
          })
          console.log(this);
      }
      // Use bind to bind this when called
      handleClick(){
          console.log(this);
      }
      render() {
          return (
              <>     
                  <div className={myStyle.main} onClick={this.handleClick.bind(this)}>Use bind to bind this when called</div>
              </>)}}Copy the code
// This function has its own scope, so you need to bind() it, or use the arrow function to change the this pointer
   increment(){
        this.setState({
            // Since count is part of the call to state, we must add this.state
            count:this.state.count+=1
        })
        console.log(this);
   }
   decrement=() = >{
        this.setState({
            count:this.state.count-=1
        })
        console.log(this);
   }
    render() {
        return (
            <div>
                <h3>Components of the state</h3>
                <div>{this.state.count}</div>
                <button onClick={this.increment.bind(this)}>increase</button>
                <button onClick={ this.decrement} >To reduce</button>
            </div>
        );
    }
Copy the code
8.2 Conditional Rendering
  • Conditions apply colours to a drawing

    • React is not written like vue. You can use judgments by adding a V-if attribute to the tag. React is used in the same way as js. if… Else and ternary operators
     render() {
    const {dataList} = this.state
    // Conditional render, if... The else mode
    let myDiv = ' '
    if (true) {
    // Tags assigned to variables can be rendered in HTML during the render function
      myDiv = (
            <div>On the test<p>1111</p>
              <span>2222</span>
              <img src="http://pic1.win4000.com/wallpaper/2020-10-21/5f8f95f2a49e2.jpg" alt=""/>
            </div>)}else{
      myDiv = <div>Under test</div>
    }
    return (
      <div>
        <ul>{myDiv} // conditional render triadic operation (loop traversal in the middle) dataList. Length? dataList.map((item,index)=>{ return<li key={index}>{item.title}</li>
                })
            :
              <div>No data currently available</div>
          }
        </ul>
      </div>)}Copy the code
  • To iterate over

    • React loops through render are different from vue applets, which can be used by negotiating property names like V-for. React uses the JSX syntax, so its traversal rendering is similar to the JS loop traversal
  this.state= {
      myList:[
          {
              name:'ime'.age:10.sex:"Male"
              ,jobs: ['111'.'222'.'333']
          }
      ]
  }
 <ul>
      {
          this.state.myList.map((element,index) = >{
              return(
                  <li key={index}>
                      <span>{element.name}</span>
                      <span>{element.age}</span>
                      <span>{element.sex}</span>
                      <span>{
                          element.jobs.map((e,i)=>{
                              return <p style={{color:'pink'}} >e</p>})}</span>
                  </li>
              )
          })
      }
  </ul>

Copy the code

9. State

  • This is similar to the data in wechat mini program or Vue’s data, mainly storing data and data interaction. The way to store data is very similar to small programs.
  • React’s this.setState is similar to this. SetData in applets.
9.1 Whether setState updates are synchronous or asynchronous
  • SetState causes the view to be redrawn
  • Asynchronous in controllable cases, synchronous in uncontrolled cases
If used directly, the data is still the same value because it is asynchronous. As for why it is asynchronous, it is also beneficial to operate asynchronously.1.If setState is updated every time, the render function will be called frequently, and the interface will be constantly re-rendered, which will consume a lot of resources, resulting in low efficiency. The best way to do this is to get multiple data at once and then update it in batches2.If the state is updated synchronically, but the render function is not called, then the state and props cannot be kept in sync, and the state and props cannot be kept consistent, which creates a lot of problems during development by changing the DOM while getting the latest values1.SetState has a callback function in which the updated value can be retrievedchangeNumber(){
                this.setState({
                    message:'ha ha'
                },() = >{
                    console.log(this.state.message)
                })
            }
        2.With the componentDidUpdate function, it is triggered by component updates, at which point the new data is synchronizedcomponentDidUpdate(prevProps, prevState) {
                console.log(this.state.message)
            }

        3.useasync awaitYou can also change it to syncasync hanlerAdd(){
                await this.setState({
                    count:this.state.count+=1
                })
                console.log(this.state.count);
            }
        
        4.With native DOM manipulation, the default is also synchronous <button ID ="btn"Decrease > < / button >hanlerAdd(){
                document.querySelector('#btn').addEventListener("click".() = >{
                this.setState({
                    message:'ha ha'
                })
                console.log(this.state.message)
            })
Copy the code

React Lifecycle functions

Life cycles are ubiquitous in development today, similar to those found in applets and Vue.

List of functions:

  • componentWillMount

    • It is called only when the component is initialized, not later when the component is updated, and only once throughout its life cycle, when state can be changed.
    • Similar to onLoad of applets, Vue and Uniapp
  • render

    • React creates the virtual DOM, performs the diff algorithm, and updates the DOM tree. You can’t change state at this point.
  • componentDidMount

    • Called once after the component has rendered. Data can be requested here
  • componentWillReceiveProps

    • Not called when the component is initialized, but when the component accepts new props.
  • shouldComponentUpdate

    • Data executes before changes (state, props)
    • React performance tuning is an important part of the process. If the props and state are the same, return false to block the update, because the same property state must generate the same DOM tree. In this way, there is no need to create a new DOM tree to compare the old DOM tree with the diff algorithm, which saves a lot of performance, especially when the DOM structure is complex
  • componentWillUpdata(nextProps, nextState)

    • It is not called when the component is initialized, but only when the component is about to be updated, at which point you can change state

11.PropsTypes type detection

  • Type detection similar to TS makes the program more robust. The advantage of type detection is that as your program gets larger, you can catch a large number of errors through it.
  • PropsTypes does type checking for props
import React, { Component } from 'react';
import PropsType from 'prop-types';
export default class PropsTypeDemo extends Component {
    render() {
        return (
            <div>
                {this.props.title}
            </div>
        );
    }
}
PropsTypeDemo.propTypes = {
    title:PropsType.bool
}
// Failed prop type:
Copy the code
  • Props Types provides several types of validation
// Declare the properties as JS native types. These properties are optional
 optionalArray: PropTypes.array,
 optionalBool: PropTypes.bool,
 optionalFunc: PropTypes.func,
 optionalNumber: PropTypes.number,
 optionalObject: PropTypes.object,
 optionalString: PropTypes.string,
 optionalSymbol: PropTypes.symbol,

 // Any element that can be rendered, including numbers, strings, elements, and arrays
 optionalNode: PropsTypes.node,
 
 // a React element
 optionalElement: PropsTypes.element,
 
 // React element typeOptionalElementType: PropsTypes elementType,// An object can be any of several types
 optionalUnion: PropsTypes.oneOfType([
 	PropsTypes.string,
    PropsTypes.number,
    PropsTypes.instanceOf(Message)
 ])
 
 // Any type of required data
 requiredAny: PropsTypes.any.isRequired,
 
 // Custom validator that returns an Error object on failure. However, it is not available in console.warn and thrown exceptions, and onOfType does not take effect
 customProp:function(props, propName, componentName){
 	if(!/matchme/.test(props[propName])){
    	return new Error(
        	'Incorrect verification information'}} ### See the official documentation for more usageCopy the code

12. The routing

Routing is like taking a taxi. You name a specific place and the old driver takes you there.

  • The history mode
    • Window History provides access to the browser’s history and exposes methods and properties that allow you to move forward and backward in the history, as well as manipulating the history data in H5.
    history.back() ;	// In the historical record is backward
    history.forward();      // Move forward in the historical record
    history.go(-1);// Moves to the specified history point
    Copy the code
  • Hash pattern
    • Hash changes do not result in a browser refresh

13. Network Request, Fecth

  • Fetch and AXIos are both designed based on promise. It is helpful to learn promise knowledge first to have a better understanding of this library.
  • Fetch is much cleaner to write (using es6’s arrow function and Promise’s.then)
componentDidMount() {
/ / GET request
fetch("http://iwenwiki.com/api/blueberrypai/getIndexBanner.php").then(res= > res.json())
  .then(data= >{
    if( data.success ){ // Here is the success code returned by the back end
      console.log(data);
    }
  }).catch(err= > console.log('Error message',err))
 
 /* POST request * Ajax argument is object key-value pair * Fetch body is string type * "user_id=123123&password=123123&verification_code=123123" Fetch recognizes the type of request argument * import qs from "queryString "; * Introduces nodeJs object conversion string methods */
   fetch("http://iwenwiki.com/api/blueberrypai/login.php", {method:"POST".body: qs.stringify({ // Introduces the nodeJs object-to-string method qs.stringify
        user_id:123123.password:123123.verification_code:123123
      }),
      headers: {"Content-Type":'application/x-www-form-urlencoded'."Accept":"application/json,text/plain,*/*"
      }
   }).then(res= >res.json())
   .then(data= >{
    console.log(data);
   }).catch(err= > console.log(err))
  }
 }
Copy the code
  • In the process of network requests, there will be cross-domain problems. Different ports will lead to cross-domain problems. Generally, such problems can be solved by the back end. But there are solutions on the front end.

    • NPM install HTTP-proxy-middleware
    • Step 2 NPM run eject
    • Step 3 Create a setupproxy. js file under SRC
    // Version 0.X introduces this
    //const proxy = require('http-proxy-middleware');
    // The 1.x version introduces this
    const { createProxyMiddleware } = require("http-proxy-middleware");
    module.exports = function(app) {
      app.use(
        createProxyMiddleware("/api", {
          target: "http://localhost:3000".changeOrigin: true})); };Copy the code
    • Step 4 Perform the configuration in start.js
    // Search for devServer in start.js in scripts
    const serverConfig = createDevServerConfig(
      proxyConfig,
      urls.lanUrlForConfig
    );
    const devServer = new WebpackDevServer(compiler, serverConfig);
    // Just add it below it
    require('.. /src/setupProxy')(devServer);// The file path is its own
    Copy the code