1. Introduction to the React

    • Install official scaffolding, the back scaffolding is better, but it is recommended to try it first

      npm install -g create-react-app 
      Copy the code
    • Initialization – Creates the project

      The create - react - app project nameCopy the code
    • run

      npm start
      Copy the code
  2. JSX: Looks like a hybrid of JS and HTML, but HTML is actually implemented by JS

    React was originally designed to use JSX to describe the UI, React only does the logical layer, reactDom does the actual DOM rendering, and if moving to mobile, use other rendering libraries

    import React from 'react'; import ReactDOM from 'react-dom'; Class App extends Component {render() {return (<div className="App"> Hello world! </div> ); }} reactdom.render (<App />, // document.getelementbyid ('root') // where root is a DOM element in index.html);Copy the code

  3. Component definition

    We can also see in the code above that the React class class is a component and uses the corresponding tag

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    ReactDOM.render(
        <App />,
        document.getElementById('root')
    );
    Copy the code
    import React, { Component } from 'react'; import './App.css'; Class App extends Component {render() {return (<div className="App"> Hello world! </div> ); } } export default App;Copy the code
  4. The state and setState

    • Use {} to render variables

      Class App extends Component {render() {const name = 'hello '; return ( <div className="App"> <p>{name}</p> </div> ); }}Copy the code
    • But if data needs to be modified and the page responds to changes at the same time, you need to place the data in State and use setState to modify the data. Super (props) is a call to a parent Construtor to initialize various life cycles, this points to data like this

      class App extends Component { constructor(props) { super(props); }} render() {return (<div className="App"> <p>{this.state.name}</p> </div>); }}Copy the code
    • Use setState to modify data. Use this.state to pass a new object at a time, which has the advantage of time travel

      class App extends Component { constructor(props) { super(props); This. state = {name:' open '}; } render() {return (<div className="App"> <p>{this.state.name }</p> </div> ); }}Copy the code
  5. Attribute passing props

    <App title=" React today "/>, // when usedCopy the code
     render() {
            return (
                <div className="App">
                    <p>{this.props.title}</p>
                </div>
            );
        }
    Copy the code
  6. Conditional rendering and looping

    • Conditions apply colours to a drawing

      class App extends Component { constructor(props) { super(props); this.state = { showTitle:true }; },2000) setTimeout(() => { this.setState({ showTitle: } render() {return (<div className="App"> {this.state.showtitle? <p>{this.props.title}</p>:null} <! {this.state.showTitle&&<p>{this.props. Title}</p>} <! </div>); }}Copy the code
    • cycle

      This. State = {goodList :[{text:'web full stack architect ',price:100,id:2}, {text:'Python',price:100,id:3} ] }; render() { return ( <div className="App"> <ul> {this.state.goodlist.map(good=>{ return <li key={good.id}> < span > {good. Text} < / span > < span > ${good. Price} < / span > < / li >})} < / ul > < / div >). }Copy the code
  7. Data management and binding

    • Data binding

      • In React, due to the enforced one-way data flow, the data-bound input cannot be modified bidirectionally like vUE
      <input type="text" value={this.state.add} onChange={(e)=>{this.setState({add:e.target.value)}} /> {/* Since value is bound to this.state react, the value will be monitored by this.state. We use this to implement our bidirectional binding */} {/* We use e.target.value to get the value we entered, and then we modify the data in state, and then our input value is automatically modified */}Copy the code
      • The implementation adds data from the input to the goodList data of the state above
      < button onClick = {() = > {enclosing handleAdd ()}} > add < / button >Copy the code
      handleAdd(){
          this.setState({
              goodlist:[...this.state.goodlist,{text:this.state.add,price:20}],
              add:''
          })
      }
      Copy the code
    • event

      OnChange ={this.handlechange}; onChange={this.handlechange}; onChange={this.handlechange}; If you pass handleChange as an argument to the current component, the component will call its own internal this. The orientation of this function has changed because it is intended for someone else (who uses this function, to whom this refers).

      onChange={this.handleChange}
      Copy the code
      handleChange(e){
       this.setState({
           add:e.target.value 
       })
      }
      Copy the code

      There are three solutions to the above problem

      • At the constructor(props) {}

        this.handleChange = this.handleChange.bind(this);  
        Whenever this function is executed, this is the this of our current component
        Copy the code
      • Use the arrow function to solve the this pointing problem

        <input type="text" value={this.state.add} onChange={(e)=> this.handlechange (e)} /> // But if the parameter is passed OnClick ={this.handleclick (I)} // This function needs to carry an I argument // so it needs to use an anonymous function to carry I.  //onClick = {()=> this.handleclick (I)} // This closure keeps I referencing renderSquare's I //----- the function passing arguments requires two arrow functionsCopy the code
      • Using bind(this) directly on onChange is not recommended

        <input type="text" value={this.state.add} onChange={(this.handlechange.bind (this)}Copy the code
      • Use the arrow function directly when defining handleChang

        handleChange=(e)=>{
            this.setState({
                add:e.target.value
            })
        };
        Copy the code
  8. Function components:

    If a component is rendered only according to props and has no internal state, it can be implemented as a functional component

    If you look at functional components, there is a difference between props and class components. Functions are passed as an argument without this

    The class component has this, usually this. Props

    // function Title(props) {// React function props (props) {// function Title <div> <h2>{props. Title}</h2> <hr/> </div>} <Title Title ={this.props. Title} /> // Use as a componentCopy the code
  9. Component communication

    Communicate through props

    Import React from 'React' function Totol({cart}){return <span> Total price :{cart.reduce((sum,a)=>{return sum += a.price* a.ount  },0)} </span> } class Cart extends React.Component{ render() { return <div> <table border="1"> <thead> <tr> < th > brand name < / th > < th > price < / th > < th > < / th > < th > total price < / th > < / tr > < thead > < tbody > {this. Props. Data. The map (good = > {return < tr key={good.text}> <td>{good.text}</td> <td>{good.price}</td> <td>{good.count}</td> <td>{good.count*good.price}</td> </tr> })} {/ * use components to do a total * /} < tr > < td colSpan = "4" align = "right" > < Totol cart = {this. Props. Data} / > < / td > < / tr > < / tbody > < / table > </div> } } export default CartCopy the code
    AddCart(good){ let cartIndex; const cartGood = this.state.cart.find((value,index) => { if (good.text === value.text) { cartIndex = index; return true } }); If (cartGood){// Let newCart = [...this.state. Cart]; newCart[cartIndex].count+=1; this.setState({ cart:newCart }) } else{ this.setState({ cart:[...this.state.cart,{ text:good.text, price:good.price, count:1 }] }) } } <Cart data={this.state.cart}/>Copy the code
  10. React each time requires setState to use a new object {to implement something like time travel

    // Add a new state cartHistory:[] to record the data that will be operated on each operation, Then click return the corresponding steps cartHistory enclosing setState ({cartHistory: [..... This state cartHistory, enclosing the state. The cart]}) resetCart (I) { / / click event handling this. SetState ({cart: this. State. CartHistory [I]})}Copy the code
  11. Virtual DOM

    The virtual DOM builds an abstraction layer on top of the DOM. Any changes made to data and state are automatically and efficiently synchronized to the virtual DOM, and then synchronized to the DOM in batches.

    In React, the result of render execution is not a real DOM node, but a JavaScript object, called a virtual DOM.

    With batch processing and efficient Diff algorithms, the virtual DOM can “refresh” entire pages at any time without worrying about performance, because the virtual DOM ensures that only the parts of the interface that really change are actually DOM manipulated.

    • Traditional APP:

    • React App:

    • InnerHTML: Render HTML string + recreates all DOM elements
    • Render virtual DOM + diff + update necessary DOM elements
    • React maintains a virtual DOM tree in memory, and reads or writes to the tree, actually to the virtual DOM. React automatically updates the virtual DOM when the data changes, compares the new virtual DOM to the old one, finds the changes, generates a DIFF, puts the DIFF in a queue, and finally updates the diFF to the DOM in batches.
  12. The life cycle

    The React lifecycle is divided into three states: 1. Initialization 2. Update 3. The destruction

    • Initialize the

      1. getDefaultProps()

        This method will only be called once, and getDefaultPops will not be called again for any subsequent applications of the component class. The object returned can be used to set the default props(short for properties) value.Copy the code
      2. getInitialState()

        This method is called once and only to initialize the state of each instance. In this method, the props of the component can be accessed. Each React component has its own state, which differs from props in that state exists only inside the component and is shared across all instances. There is a difference between getInitialState and getDefaultPops. GetDefaultPops is called only once for the component class and will not be called for subsequent applications of the class, while getInitialState is called for each component instance. And only once.Copy the code
      3. componentWillMount()

        This method is called before the first (that is, only once) render and is the last chance to modify state before the render method is called.Copy the code
      4. render()

        This method creates a virtual DOM that represents the output of the component. The Render method is the only method required for a component. The render method needs to satisfy the following points: 1. Only this. Props and this. You can return NULL,false, or any React component 3. Only one top-level component can appear, and no set of elements can be returned. The render method, which cannot modify the DOM, returns not a real DOM element, but a virtual representation of an object, similar to a DOM tree structure. React is efficient for this reason.Copy the code
      5. componentDidMount()

        Called once after the component has renderedCopy the code
    • Update:

      When the component is rendered and the user can interact with it, such as a mouse click, a finger tap, or some other event that causes the application state to change, you will see the following methods called in turn

      1. componentWillReceiveProps(nextProps)

        Components of props attribute can be changed by the parent component, then componentWillReceiveProps is invoked in the future. You can update state in this method to trigger the Render method to rerender the component.Copy the code
      2. shouldComponentUpdate(nextProps, nextState)

        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. This saves a lot of performance by eliminating the need to create a new DOM tree to compare with the old DOM tree, especially when the DOM structure is complex and this method is not required and is not used in most cases in development.Copy the code
      3. componentWillUpdata(nextProps, nextState)

        This method is similar to componentWillMount. Before the component receives the new props or state for rerendering, ComponentWillUpdate (Object nextProps, Object nextState) is called. Don't update props or state in this context.Copy the code
      4. render()

        The component is rendered again after the updateCopy the code
      5. componentDidUpdate()

        This method is similar to componentDidMount in that componentDidUpdate(Object prevProps, Object prevState) is called after the component has been re-rendered. You can access and modify the DOM hereCopy the code
    • The destruction

      1. componentWillUnmount()

        Whenever React uses a component, the component must be uninstalled from the DOM and then destroyed. This method is used to remove all cleanup and destruction for componentWillUnmout. Such as created timers or event listeners.Copy the code