[React] detailed tutorial

preface

1. Contrast between react and vue

1.1 what is modularity

It is analyzed from the perspective of code

Separate some reusable codes into separate modules; Facilitate the maintenance and development of the project

1.2. What is componentization

It is analyzed from the perspective of UI interface

Separate reusable UI elements

1.3 benefits of componentization

With the increase of project scale, there are more and more components in hand;

It is very convenient to splice the existing components into a complete page

1.4 how to realize componentization in vue

Pass vue file to create the corresponding component

template structure script behavior style

1.5. How to realize Componentization of React:

React has the concept of componentization, but it is not like Component template files such as vue

In React, everything is represented by JS

2. Virtual DOM

2.1 what is the essence of DOM

The concept in the browser uses js objects to represent the elements on the page, and provides APIs for operating dom objects

2.2. What is virtual DOM in React

Concept in the framework: use js objects to simulate Dom and DOM nesting on the page

2.3. Why should we implement virtual DOM (the purpose of virtual DOM)

In order to realize the funny update of DOM elements in the page

1, Introduction to react

1. What is react

  • react is an open source JavaScript library that renders data into HTML views

2. Why learn react

  • Native JavaScript operation DOM is cumbersome and inefficient (DOM-API operation UI)
  • Using JavaScript to directly operate DOM, the browser will do a lot of redrawing and rearrangement
  • Native JavaScript has no component coding scheme, and the code reuse rate is low

3. Characteristics of react

  • Adopt component mode and reputation coding to improve development efficiency and component reuse rate
    • Imperative coding: command the machine how to do things, say and do step by step
    • Nominal coding: tell the machine what it wants and how to do it
  • In React Native, React syntax can be used for mobile terminal development.
  • Use the virtual DOM + excellent Diffing algorithm to minimize the interaction with the real dom

2, react first experience

1. Required dependencies

// If crossorigin does not have this attribute, the browser will hide the error reporting problem of cross domain pages
// Adding this attribute enables the browser to get the specific error messages in the import script

// babel.js: ES6 to ES5, jsx to js
// react.development.js: after the introduction of react core library, react objects are added globally
// react-dom.development.js: after the introduction of react extension library (help operate DOM), ReactDOM objects are added globally

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

2. Using jsx

  1. Full name: JavaScript XML
  2. react defines a js extension syntax similar to XML: js+XML
  3. jsx is the syntax for the original js to create a virtual DOM (react. Createelement())
  4. Function: used to simplify the creation of virtual DOM
    1. Not a string, not an HTML/XML tag
    2. The final generation is a js object
  5. jsx syntax rules
    1. When defining a virtual DOM, do not write quotation marks
    2. Use {} when mixing JS expressions into tags
      1. JS expression: an expression produces a value (i.e. a return value), which can be placed anywhere a value is required
        //  1. Variable
        a
        //  2. Operation expression
        a+b
        //  3. The function call expression function returns undefined by default
        demo(1)	
        //  4. The map method of the array has a return value
        arr.map()
        //  5. Define a function and return the function itself
        function test () {}
        
      2. JS statement: JS code blocks have no return value, but only control the direction of the code
        if(){}
        
        for(){}
        
        switch(){case:xxx}
    3. The class name of the style specifies to use className instead of class (to distinguish it from es6 class)
    4. The inline style should be written in the form of style={{key:value}}
    5. The virtual DOM has only one root tag
    6. The label must be closed
    7. Label initials
      1. If it starts with a capital letter, react will render the corresponding component. If the component is not defined, an error will be reported
      2. If it starts with a lowercase letter, the tag will be converted to a tag with the same name in html. If there is no corresponding tag, an error will be reported
    8. <script type="text/babel"></script>
    9. It makes it easier to create virtual dom nodes

3. Virtual DOM

  • An Object of type Object (general Object) in essence
  • The real DOM is heavier than the virtual dom. The virtual DOM is used inside React and does not need so many attributes on the real dom
  • The virtual DOM will eventually be transformed into a real DOM by React and presented on the page.

4. Understanding of module and component, modularization and componentization

4.1. js module (just split js)

  • understand:
    • A js program that provides specific functions externally is generally a js file
  • Why should it be disassembled into modules:
    • As business logic increases, code becomes more and more complex
  • effect:
    • Reuse js, simplify the writing of js and improve the running efficiency of js

4.2 components ()

  • understand:
    • A collection of code and resources used to achieve local functional effects (html/css/js/image, etc.)
  • Why?
    • The function of an interface is more complex
  • effect:
    • Reuse coding, simplify project coding and improve operation efficiency

4.3 modularization

When the js of an application is written in modules, the application is a modular application

4.4. Modularization

When an application is implemented in a multi-component way, the application is a component-based application

3, React component oriented programming

1. Component details

1.1 functional components

  • Component defined by function (applicable to the definition of simple component)
     <script type="text/babel">
          function Demo() {
          // After babel is translated, open the strict mode. this cannot point to window and becomes undefined
            console.log("this", this);
            return <h1>Function component</h1>;
          }
          ReactDOM.render(<Demo />, document.getElementById("app"));
          
           // Executed reactdom What happened after render?
          // 1. React parses the component label and finds the Demo component
          // 2, it is found that the component is defined by function, and then the function is called.
          // 3. Convert the returned virtual DOM into a real DOM, and then render it in the page
         
        </script>

1.2 class I components

  • Components defined using es6 class class (for complex components)
        <script type="text/babel">
          // When using class components, you must inherit react Component
          class MyComponent extends React.Component {
            // Constructors are not required
            // But there must be render and return value
            render() {
                // Although we didn't instantiate new MyComponent() manually, reactdom Render helped us instantiate
                // Therefore, render exists on the prototype object of MyComponent for instance use 
                // Here, this in render points to the instance object of MyComponent
              console.log("render Medium this", this); // Point to the instance object of MyComponent mycomponent {...}
              return <h1>I am a component defined by class (using the definition of complex component)</h1>;
            }
          }
          // Render components to the page;
          ReactDOM.render(<MyComponent />, document.getElementById("app"));
          
          //Executed reactdom render(<MyComponent />, ...)) After that, what happened?
          // 1. React parsed the component label and found the MyComponent component
          // 2. It is found that the component is defined using a class, and then new comes out the instance of the class, and calls the render method on the prototype through the instance
          // 3. Convert the virtual DOM returned by render into real DOM, and then render it in the page
     
        </script>

2. Three characteristics of component instances (class components / hooks)

2.1,state

2.1.1 understanding

  • state is the most important attribute of the component object, and the value is the object
  • The component is called "state machine", which updates the corresponding page display by updating the state of the component (re rendering the component)

2.1.2. Strong attention

  • this in the render method of the component is the component instance object
  • this is undefined in the method defined by the component. How to solve it?
    • Force binding this; Through bind() of function object
    • Arrow function
  • Status data cannot be modified or updated directly
<script type="text/babel">
      // Create component
      class MyComponent extends React.Component {
        //   How many times does the constructor call? Once
        constructor(props) {
          super(props);

          //   Initialization status
          this.state = {
            isHot: false,
          };

          //   this points to the solution
          // This on the left changeWeather is the changeWeather variable of the current class
          // This on the right Changeweather is a method on a class prototype object that points its this to the current class
          this.changeWeather = this.changeWeather.bind(this);
        }

        // How many times does render call? 1+n times, 1 is initialization and N is the number of status updates
        render() {
          // render exists on the prototype object of MyComponent class
          // The instance of MyComponent called by my this object points to MyComponent
          // Read status
          const { isHot } = this.state;
          console.log("render Medium this", this); // Point to the instance object of MyComponent mycomponent {...}
          // onclick is not an html dom event. onclick cannot be compared with a native event
          // This is actually assigning the changeWeather method on the instance to onClick
          // Then use onClick to directly call the changeWeather event. At this time, this point is not an instance
          return (
            <h1 onClick={this.changeWeather}>
              Today's weather{isHot ? "scorching hot" : "pleasantly cool"}
            </h1>
          );
        }

        // How many times is changeWeather called? Adjust several times
        changeWeather() {
          // changeWeather is on the prototype object of the instance for use by the instance
          // Because changeWeather is a callback of onClick, it is not called through an instance, but directly
          // The method in the class turns on the local strict mode by default, so this in chagneWeather is undefined
          console.log("changeWeather", this);

          //   Important note: the state must be updated through setState, and the update is a merge, not a replacement
          //   setState is a merge operation, which will not affect other properties in the state, not a replacement
          this.setState({ isHot: !this.state.isHot });
        }
      }
      // Render components to the page;
      ReactDOM.render(<MyComponent />, document.getElementById("app"));

      //   ReactDOM. What has render done to write;
      //   1. First judge the incoming component label
      //     If it is lowercase, it will render the tag in the corresponding html
      //     If it is capitalized, it determines whether it is a function component or a class component
      //         If it is a function component, find the corresponding function component for rendering
      //         If it is a class component, instantiate it first, and then make the instantiation call the render method on the prototype to render
      //     Convert the returned virtual dom tree to the number of real DOMS
    </script>

2,props

2.1. Class components receive props value

<script type="text/babel">
      class Person extends React.Component {
        // There are only two functions of constructors
        // 1. Initialization data status (can be abbreviated)
        // 2. Bind this object to the event (it can be abbreviated by assignment statement + arrow function)
        // Conclusion: omit if you can

        constructor(props) {
          // Whether the constructor receives props and passes it to super depends on whether you want to access props through this in the constructor
          super(props);
          console.log("props", props);
          // After passing props in super, you can use this Props access props
          console.log("this.props", this.props);
        }

        render() {
          const { name, age, sex } = this.props;
          return (
            <ul>
              <li>{name}</li>
              <li>{sex}</li>
              <li>{age + 1}</li>
            </ul>
          );
        }
      }

      let data = { name: "cz", age: "18", sex: "male" };
      // The attribute object in js cannot be expanded directly, but it is processed by babel and react core library in react, so the object can be expanded directly with the expansion symbol here
      ReactDOM.render(<Person {...data} />, document.getElementById("app"));
      ReactDOM.render(
        <Person name="xp" age="16" sex="female" />,
        document.getElementById("app")
      );
    </script>

2.2. Function component receives props value

<script type="text/babel">
      function Person(props) {
        const { name, sex, age } = props;
        return (
          <ul>
            <li>{name}</li>
            <li>{sex}</li>
            <li>{age + 1}</li>
          </ul>
        );
      }

      let data = { name: "cz", age: 18, sex: "male" };
      // js objects cannot be expanded directly, but in react, babel and react core libraries handle them, so you can expand the objects directly with the expansion symbol
      ReactDOM.render(<Person {...data} />, document.getElementById("app1"));
      ReactDOM.render(
        <Person name="xp" age={16} sex="female" />,
        document.getElementById("app2")
      );
    </script>

2.3 refs (do not overuse ref)

  1. understand
    1. Tags in components can identify themselves by ref (alternative id)
  2. Writing method
    1. String writing
      //String writing is not recommended (obsolete and will be removed in the future)
      //String writing will cause some problems (inefficient)
      <input ref="input1" type="text" placeholder="Please enter" />
      // obtain
      this.refs.input1

    2. Callback function writing
      • The first inline method
            <script type="text/babel">
              class Demo extends React.Component {
                showData = () => {
                  console.log(this);
                  // If the written refs is written as a callback, the node node is directly assigned to the input1 variable of the instance
                  // You can't take const {input1} = this from refs refs;
                  // Directly on the instance
                  const { input1 } = this;
                  alert(input1.value);
                };
                showData2 = () => {
                  const { input2 } = this;
                  alert(input2.value);
                };
                render() {
                  return (
                    <div>
                      {/*
                        1,After the render function is executed, the jsx statement in the render function is executed
                        2,If ref is a callback in jsx, the callback inside will be triggered
                         (The callback of a specific tag will be react processed, and the expression of any tag will be processed, but the callback will not, and an error will be reported, for example: XXX = {() = > {...}) error
                        3,An arrow function is triggered here
                        4,Running the arrow function assigns the parameter in the arrow function (this parameter is the current node processed by react) to this input1
                        5,Because the arrow function itself does not have this, it will find this of render upward, that is, the current instance
                        6,Therefore, the current node node is assigned to the input1 variable of the instance
                      */}
                      <input
                        ref={(currentNode) => {
                          this.input1 = currentNode;
                        }}
                        type="text"
                        placeholder="Click the button to prompt data"
                      />
                      <button style={{ margin: "0 10px" }} onClick={this.showData}>
                        Click the input box on the left of the prompt
                      </button>
                      {/* This is the abbreviation of refs callback */}
                      <input
                        onBlur={this.showData2}
                        ref={(c) => (this.input2 = c)}
                        type="text"
                        placeholder="Lost focus prompt data"
                      />
                    </div>
                  );
                }
              }
              ReactDOM.render(<Demo />, document.getElementById("app1"));
            </script>

      • The second kind of binding method
        <script type="text/babel">
              class Demo extends React.Component {
                state = { isHot: true };
        
                showInfo = () => {
                  const { input1 } = this;
                  alert(input1.value);
                };
        
                changeWeather = () => {
                  const { isHot } = this.state;
                  this.setState({
                    isHot: !isHot,
                  });
                };
        
                saveInput = (currentNode) => {
                  console.log("currentNode", currentNode);
                };
                render() {
                  const { isHot } = this.state;
                  return (
                    <div>
                      <h2>It's a fine day today{isHot ? "scorching hot" : "pleasantly cool"}</h2>
                      {/*
                        1,This is the inline writing method (the way to directly put the executed code in the callback function)
                        2,This way of writing will cause the current function to be reloaded every time the render is updated (excluding the first render)
                          It will be executed twice. The first time, the parameter will be assigned to null, and the second time, the current dom node will be bound
                        3,It will not affect the actual code and can still be used
                      */}
                      <input
                        ref={(currentNode) => {
                          this.input1 = currentNode;
                          console.log("I was called", currentNode);
                        }}
                        type="text"
                      />
                      <button onClick={this.showInfo}>Click the prompt to enter the data</button>
                      <button onClick={this.changeWeather}>Click me to change the weather</button>
                      {/*
                        This is a class binding callback
                        This method can avoid the problem of ref loading twice
                      */}
                      <input ref={this.saveInput} type="text" />
                    </div>
                  );
                }
              }
              ReactDOM.render(<Demo />, document.getElementById("app1"));
            </script>

      • The third is createRef (the most recommended method)
        <script type="text/babel">
              class Demo extends React.Component {
                // React. A container can be returned after the createref call
                // The container can store nodes represented by ref
                // This container is specially designed for special personnel. Only one container can be stored. The one behind will cover the current one
                myRef = React.createRef();
                showData = () => {
                  console.log("myRef", this.myRef); // {current: input}
                };
                render() {
                  return (
                    <div>
                      <input
                        ref={this.myRef}
                        type="text"
                        placeholder="Click the button to prompt data"
                      />
                      <button style={{ margin: "0 10px" }} onClick={this.showData}>
                        Click the input box on the left of the prompt
                      </button>
                    </div>
                  );
                }
              }
              ReactDOM.render(<Demo />, document.getElementById("app1"));
            </script>

    3. event processing
      • Specify the event handler function through the onXxx attribute (note case)
        • React uses custom (composite) events instead of native DOM events - for better compatibility
        • Events in React are handled through event delegation (delegated to the outermost element of the component) -- for efficiency
      • Via event Target gets the DOM element object of the occurrence time -- don't overuse ref
      • When the element of the event happens to be the element we need to get, we don't need to write ref

3. Collect form data

  • Uncontrolled components
  • Controlled components
    • The dom of all input classes in the form can get the input value at the same time

4. Higher order function, coritization

4.1 higher order function

  • If a function conforms to any of the following two specifications, the function is a high-order function.
    • If the parameter received by A function is A function, then A can be called A higher-order function
    • If the return value of A function call is still A function, then A can be called A higher-order function
  • Common higher order functions
    • promise
    • setTimeout
    • Common array methods map reduce forEach

4.2 function coritization

  • The function coding form of receiving parameters for many times and finally unified processing is realized by continuing to return the function through function call

5. Life cycle

5.1 understanding

  • Components go through some specific stages from creation to death
  • The React component contains a series of dog sub function life cycle callback functions, which will be called at a specific time
  • When defining components, we will do specific work in specific life cycle callback functions

5.2 life cycle process (old)

 

  • Initialization phase: by reactdom Render() trigger ----- initial rendering
    • constructor
    • componentWillMount()
    • render()
    • componentDidMount() -- common
      • Initialization is usually done in this hook
        • Start timer
        • Send network request
        • Subscribe to messages
  • Update phase: this. By the component Triggered by setstate() or parent component render
    • shouldComponentUpdate()
    • componentWillUpdate()
    • render()
    • componentDidUpdate()
  • Uninstall components: by reactdom Unmountcomponentatnode() trigger
    • componentWillUnmount() -- common
      • Usually do some finishing work in this hook
        • off timer
        • Unsubscribe message
  • The component receives new props hooks (the first received one does not count)
    • componentWillReceiveProps()

5.3 life cycle (New)

  • All hooks with will, except those to be unloaded, shall be added with UNSAFE_ Prefix
  • These hooks are still the previous ones and will be discarded in the future, which will increase their current use cost
    • componentWillMount() ----> UNSAFE_componentWillMount()
    • componentWillUpdate() ----> UNSAFE_componentWillUpdate()
    • componentWillReceiveProps() ----> UNSAFE_componentWillReceiveProps()
  • Added 2 new hooks
    • getDerivedStataeFromProps
    • getSnapshotBeforeUpdate

 

  • Initialization phase: by reactdom Render() trigger - initial rendering
    • constructor()
    • getDerivedStateromProps()
    • render()
    • Componentdidmount() = = = > common
      • Generally, some initialization is done in this hook
        • Start timer
        • Send network request
        • Subscribe to messages
  • Update phase: this. By the component Setstate() or parent component re render trigger
    • getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()
  • Uninstall components: by react Unmountcomponentatnode() trigger
    • componentWillUnmount() = = = = common
      • Usually do some beginning and end things in this hook
        • off timer
        • Unsubscribe message

6. diff algorithm

7. React sends a network request

  • Cross domain

3, React routing

1. Understanding of SPA

  • single page web application (SPA).
  • The whole application has only one complete page.
  • Clicking the link in the page will not refresh the page, but only make a partial update of the page
  • All data needs to be obtained through ajax requests and presented asynchronously at the front end.

2. Understanding of routing

  • What is routing?
    • A key:value mapping relationship
    • key is the path, and value may be function or component
  • Routing classification
    • Back end routing
      • Understanding: value is a function used to process requests submitted by clients
      • Registered route: router get(path, function(req, res))
      • Working process: when the node receives a request, it finds the matching route according to the request path, calls the function in the route to process the request and return the response data
    • Front end routing
      • Browser side routing. value is the component, which is used to display the page content.
      • Register route:
      • Working process: when the path of the browser changes to / Test, the current routing component will change to Test component

3. Basic use of routing

  • Define the navigation area and display area in the interface
  • The a label in the navigation area is changed to the Link label
// To is the name you want to display after the domain name corresponding to the component
<Link to='/Demo'>Demo</Link>
  • Write the Route label in the display area for path matching
// First introduce the Demo component
import Demo from './components/demo'
// Render as long as it corresponds to the path after to in the link
<Route path='/Demo' component={Demo}>
  • The outermost side of the is wrapped with a or label
    • All routes can only be wrapped by the same route label to play the role of matching rendering

4. Routing components and general components

  • Different writing methods
    • General components
      • It can be modified as a routing component through export default withrouter (component name)
    • Routing component:
  • Different storage locations
    • General components: components
    • Routing component: pages
  • Accept props differently
    • General components: what is passed and what is received when writing components
    • Routing component: the received routing information has three fixed attributes
      • history
      • location
      • match

5. NavLink and package NavLink

  • NavLink can highlight routing links, and specify the highlight style name through the activeClassName attribute
  • Label body content is a special label attribute
  • Through this props. Children can get the label body content

6. Use of switch

  • Usually, path and component are one-to-one correspondence
  • Wrapping the Switch tag with the Route tag can improve the efficiency of Route matching (the previous one will not be matched)

7. Solve the problem of losing the page style of multi-level path refresh

  • publich/index. Path when introducing styles into HTML/ Modify to / (common)
  • publich/index. Do not write when introducing styles into HTML/ Write% PUBLIC_URL% (common) (in react scaffold)
  • Using HashRouter

8. Strict matching and fuzzy matching of routing

  • Fuzzy matching is used by default (simply remember: the [entered path] must include the [path to match] in the same order)
  • Turn on strict matching:
  • The strict mode should not be opened casually. It needs to be opened again. Sometimes, it will lead to the inability to continue to match the secondary route

9. Use of Redirect

  • Generally, all routes are registered at the bottom. When all routes cannot be matched, jump to the route specified by Redirect
  • Specific code:
<Switch>
    <Route path="/cz/home" component={Home}></Route>
    <Route path="/about" component={About}></Route>
    <Redirect to="/cz/home" />
  </Switch>

10. Nested routing

  • To register a sub route, write the path value of the sub route
  • Routes are registered in the order in which they are registered

11. Pass parameters to routing components

  • params parameter
// Routing link (with parameters)
<Link to='/detail/03/cz'>details</Link>
// Register route (claim receive)
<Route path="/detail/:id/:name"></Route>
// Receive parameters
const {id,name}= this.props.match.params

12. search parameter

// Routing link (with parameters)
 <Link to="/home/news?id=03&name=cz">news</Link>
 // Register route (no need to declare receiving)
 <Route path="/home/news" component={News}></Route>
 // Receive parameters (the obtained urlencoded encoded string can be parsed through qs.parse)
 const {search} = this.props.location
 const searchQuery = qs.parse(search.slice(1))

13. state parameter

// Routing link (with parameters)
 <Link to={{pathname:'/home/detail',state:{id:'03',name:'cz'}}}>news</Link>
 // Register route (no need to declare receiving)
 <Route path="/home/detail" component={Detail}></Route>
 // Receive parameters (the obtained urlencoded encoded string can be parsed through qs.parse)
 const {state} = this.props.location

14. Programmed route navigation

  • With this props. The API on the history object is responsible for the operation route jump, forward and backward
this.props.history.push()
this.props.history.replace()
this.props.history.goBack()
this.props.history.goForward()
this.props.history.go()

15. Differences between BrowserRouter and HashRouter

  • The underlying principle is different:
    • BrowserRouter uses the history API of H5 and is not compatible with versions below IE9
    • HashRouter uses the hash value of the URL
  • URLs behave differently
    • There is no in the path of BrowserRouter#
    • HashRouter uses the hash value of the URL
  • Impact on route state parameters after refresh
    • BrowserRouter has no effect because the state is saved in the history object
    • The refresh of HashRouter will result in the loss of route state parameters!!!
  • Note: HashRouter can be used to solve some problems related to path errors

4, Redux

1. What is Redux

  • redux is a JS library dedicated to state management (not a react plug-in library).
  • It can be used in react, angular, vue and other projects, but it is basically used in conjunction with react.
  • Function: centrally manage the shared state of multiple components in react application.

2. Under what circumstances do you need to use redux

  • The status of a component needs to be available (shared) by other components at any time.
  • One component needs to change the state of another component (Communication).
  • General principle: don't use it if you can. If you don't have to work hard, consider using it.

3. redux workflow

4. Three concepts of redux

4.1,action

  1. Object of action
  2. Contains 2 attributes
    • type: identifies the attribute. The value is a string. It is unique and necessary
    • Data: data attribute, any value type, optional attribute
  3. example
    {
        type:'add',
        data:{name:'cz',age:18}
    }

4.2,reducer

  1. Used for initialization status and machining status
  2. During processing, a pure function of a new state is generated according to the old state and action
  3. Pure function:
    • As long as you have the same input, you must get the same output
    • The following constraints must be observed
      • Parameter data cannot be overwritten
      • There will be no side effects, such as network requests, input and output devices
      • Cannot call date Now () or math Impure methods such as random ()
  4. Why is reducer a pure function
    • Firstly, reducer is designed to accept an old state and action and return a new state
    • If impure functions are used, the returned state cannot be guaranteed
    • For example, value=getValue+1; GetValue is a request. If it is clear that there is an error, the returned state will become uncertain, and the data obtained by the front end is uncertain, so it will lose its value as a reducer

4.3,store

  1. An object that links state, action, and reducer together

5. redux usage

5.1. Remove the state of the component itself

5.2. Create a store js

  • The createStore function in redux is introduced to create a store
  • When calling createStore, you need to pass in a reducer that serves you
  • Expose store object
  • Create reducer js
    • The essence of reducer is a function. It accepts two parameters, preState and action, and returns the processed state
    • reducer has two functions:
      • Initialization status
      • Processing status
    • When the reducer is called for the first time, it is automatically triggered by the store, and the passed preState is undefined
  • Detect the change of state in the store in the entry file js, and re render once the change occurs
  • Note: redux is only responsible for managing the status. As for the display of the status change driven page, we have to write it ourselves
import store from '../redux/store'
// Monitor store status changes
store.subscribe(()=>{ReactDOM.render(<App />,document.getElementById('root'))})

6. Asynchronous use of redux

  • It is clear that the delayed action does not want to be handed over to the component itself, but to the action
  • When do I need an asynchronous action
    • You want to operate on the status, but the specific data is returned by the asynchronous task
    • Instead of returning a general object, the function that creates the action returns a function in which asynchronous tasks are written
    • After the asynchronous task has a result, a synchronous action is distributed to actually operate the data
  • Note: asynchronous actions do not have to be written. You can wait for the results of asynchronous tasks before distributing actions.
  • Specific steps
    • You need to introduce the applyMiddleware method in the store page to parse the middleware
    • Download and introduce react thunk middleware to parse the function returned by action
store.js
// This question is specifically used to expose a store object. The whole application has only one store object
// createStore is introduced to create the core store object in redux
// Applymeddleware is introduced to deal with middleware
import { createStore,applyMiddleware } from 'redux'
// Introduce a reducer that serves the count component
import countReducer from './count_reducer.js'
// The middleware Redux thunk, which can handle asynchronous methods with action as function, is introduced
import thunk from 'redux-thunk'
export default createStore(countReducer,applyMiddleware(thunk))

action.js
// When the action is a method, it is asynchronous. The store does not recognize the action as a function, which needs to be processed by middleware
export const actionAsyncAdd = (data,time) => {
    // store will pass in dispath when calling this method
    return (dispatch)=>{
        setTimeout(()=>{
            dispatch(actionAdd(data))
        },time)
    }
}

7. React Redux usage

7.1 schematic diagram

 

7.2. Use of react Redux

  1. Store creation is the same as that of Redux. There is only one store globally
  2. Wrap it outside the container and pass it into the store
    • The incoming store can be obtained in the first function passed in connect
  3. The connect method in react Redux is introduced to wrap sub components to form parent-child relationship and expose
    export default connect(
        state => ({ count: state.count }), // Receive data from store
        {
          jia: ()=>{},  // Method of passing in operation data status
          jian: ()=>{},
        })(Count);  // Pass subcomponents in

  4. In the subcomponent, props is used to obtain and operate the data and methods transmitted by connect
  5. React Redux optimization
    • Container components and UI components are integrated into one file
    • You don't need to pass the store to the container component, just give the package one
    • After using react redux, you don't need to detect the change of state in redux by yourself. The container component can complete this work automatically
    • mapDispatchToProps can also be abbreviated to an object
    • How many steps does a component need to go through to "deal with" redux?
      • Define UI components
      • Introduce connect to generate a container component and expose it, which is written as follows
        connect(
            state=>({key:value}) //Mapping state
            {key:xxxxAction} //Method of mapping operation state
        )(UI assembly)

      • In the UI component, use this props. XXXX read and operation status

8. reducer merge data sharing

// This question is specifically used to expose a store object. The whole application has only one store object
// createStore is introduced to create the core store object in redux
// Applymeddleware is introduced to deal with middleware
// combineReducers is introduced to merge reducers
import { createStore,applyMiddleware,combineReducers } from 'redux'
// Introduce a reducer that serves the count component
import countReducer from './count_reducer.js'
// Introduce reducer serving for person component
import personReducer from './person_reducer.js'

const allReducers = combineReducers({
    count:countReducer,
    personReducer:personReducer
})
 

// The middleware Redux thunk, which can handle asynchronous methods with action as function, is introduced
import thunk from 'redux-thunk'
// Give the merged reducers to the store
export default createStore(allReducers,applyMiddleware(thunk))
  • Define a Person component and share data with the Count component through redux
  • Write reducer and action for Person component
  • Important: the Person reducer and the Count reducer should be merged by using combineReducers. The total state after merging is one object!!!
  • The store is handed over to the general reducer. Finally, when taking out the status in the component, remember to "take it in place"

5, react extension

1,setState

1.1. The first writing method: setstate ({key: value}, [callback]) -- object writing method

  • setState is a synchronous method, but the react state update caused by the call of setState is asynchronous
  • setState second optional callback parameter
    • It is called only after the status is updated and the interface is updated (after the render call)

1.2. The second writing method: setstate (updater, [callback]) - functional writing method

  • updater is a function that returns a change object
  • updater can accept state and props parameters
  • Callback is an optional callback function. It is called only after the status is updated and the interface is updated (after render is called)
  • "When" asynchronous performance "
    • There is a merge and modify strategy inside setState to optimize performance. This strategy leads to asynchronous rendering after setState
    • Therefore, when we use the api that react can control, it will reflect the "asynchronous" situation
      • React lifecycle, react events, and so on
    • When we use the api beyond the control of react, we can break away from the setState and merge the modified operation to make the setState into a synchronous operation
      • setTimeout , promise.then, ajax, binding native events

2,lazyLoad

2.1 lazyLoad of routing component

//1. Dynamically load the routing component through the lazy function of React and the import() function = = = > the routing component code will be packaged separately
	const Login = lazy(()=>import('@/pages/Login'))
	
	//2. Specify that a user-defined loading interface is displayed before loading the route packaging file through < suspend >
	<Suspense fallback={<h1>loading.....</h1>}>
        <Switch>
            <Route path="/xxx" component={Xxxx}/>
            <Redirect to="/login"/>
        </Switch>
    </Suspense>

3,Hooks

3.1 what is React Hook/Hooks?

  1. Hook is a new feature / syntax added to React 16.8.0
  2. You can use state and other React features in function components

3.2. Three commonly used hooks

  1. State Hook: React.useState()
  2. Effect Hook: React.useEffect()
  3. Ref Hook: React.useRef()

3.3, State Hook

  1. State Hook allows function components to have state and read and write state data
  2. Syntax: const [XXX, setXXX] = react useState(initValue)
  3. useState() Description:
    1. Parameter: the specified value is cached internally during the first initialization
    2. Return value: an array containing two elements. The first is the internal current status value, and the second is the function that updates the status value
  4. Setxxx() can be written in two ways:
    1. setXxx(newValue): the parameter is a non function value, which directly specifies a new status value and internally overwrites the original status value
    2. SetXXX (value = > newvalue): the parameter is a function that receives the original status value and returns a new status value, which is used internally to overwrite the original status value

3.4,Effect Hook

  1. Effect Hook allows you to perform side-effect operations in function components (used to simulate life cycle hooks in class components)
  2. Side effects in React:
    1. Send ajax request for data acquisition
    2. Set subscription / start timer
    3. Manually change the real DOM
  3. Syntax and Description:
    useEffect(() => {
    
    // Any operation with side effects can be performed here
    
    return () => { // Execute before component uninstallation
    
    // Do some finishing work here, such as clearing timer / unsubscribing, etc
    
    }
    
    }, [stateValue]) // If [] is specified, the callback function will only be executed after the first render()

  4. useEffect Hook can be regarded as a combination of the following three functions
    1. componentDidMount()
    2. componentDidUpdate()
    3. componentWillUnmount()

3.5,Ref Hook

  1. Ref Hook can store / find tags or any other data in the function component
  2. Syntax: const refContainer = useRef()
  3. Function: save label object, function and react Createref()

4,Fragment

Use:

<Fragment><Fragment>
	<></>

Function: you don't have to have a real DOM root tag

5,Context

understand:

>A communication mode between components, which is often used for communication between [ancestor component] and [descendant component]

use

  1. Create Context container object:
    1. const XxxContext = React.createContext()
  2. When rendering subgroups, wrap xxxcontext Provider, which passes data to descendant components through the value attribute:
    <xxxContext.Provider value={data}>
    		Subcomponents
        </xxxContext.Provider>
  3. Data read by descendant components:
    1. The first method: only applicable to class components
      1. static contextType = xxxContext / / declare to receive context
      2. this.context / / read the value data in the context
    2. The second way: both function components and class components can be used
      <xxxContext.Consumer>
      	    {
      	      value => ( // Value is the value data in the context
      	        What to display
      	      )
      	    }
      </xxxContext.Consumer>

be careful

context is generally not used in application development, and its encapsulated react plug-in is generally used

6. Component optimization

6.1. Two problems of Component

  1. As long as setState() is executed, even if the state data is not changed, the component will re render() = = > which is inefficient
  2. Only the current component re renders (), it will automatically re render the sub components, even if the sub components do not use any data of the parent component = = > low efficiency

6.2 efficient practices

Re render() only when the state or props data of the component changes

reason:

shouldComponentUpdate() in Component always returns true

solve:

Method 1:

Override shouldComponentUpdate() method

Compare the old and new state or props data. If there is any change, it returns true. If there is no change, it returns false

Method 2:

Using PureComponent

PureComponent overrides shouldComponentUpdate(), and returns true only when the state or props data changes

Note:

It only makes a shallow comparison between state and props data. If only the internal data of the data object changes, false is returned

Do not modify the state data directly, but generate new data

PureComponent is generally used to optimize in projects

7. Summary of component communication mode

7.1 relationship between components:

  • Parent child component
  • Sibling component (non nested component)
  • Grandparent component (cross level component)

7.2. Several communication modes:

  1. props:
    1. children props
    2. render props
  2. Message subscription - publish:
    1. Pubs sub, event, etc
  3. Centralized management:
    1. redux, dva, etc
  4. conText:
    1. Producer consumer model

7.3. Better Collocation:

  1. Parent child component: props
  2. Brother components: message subscription - publishing, centralized management
  3. Grandparents and grandchildren component (cross level component): message subscription publishing, centralized management, context (less for development, more for encapsulation plug-ins)

Keywords: Javascript Front-end React

Added by iainr on Fri, 11 Feb 2022 08:55:25 +0200