Article 1. The basis

1. What’s the role of keys in React?

  • Keys is a secondary marker that React uses to keep track of which list elements have been modified, added, or removed.
render () {
  return (
    <ul>
      {this.state.todoItems.map(({item, key}) => {
        return <li key={key}>{item}</li>
      })}
    </ul>
  )
}
Copy the code
  • React uses a key to identify components. It is an identity identifier. The same key is considered the same component by React, so that subsequent components with the same key are not created
  • When you have the key attribute, you establish a relationship with the component. React decides whether to destroy, recreate, or update the component based on the key.
  • React updates only component attributes if component attributes change. No changes, no updates.
  • React destroys the component (constructor and componentWillUnmount) and then recreates it (constructor and componentWillUnmount).

2. What happens after setState is called?

  • After calling setState in code, React merges the passed parameter objects with the component’s current state and triggers what’s known as the reconciliation process.
  • After the concatenation process, React builds the React element tree based on the new state in a relatively efficient way and starts to rerender the entire UI.
  • After React gets the element tree, React automatically calculates the node differences between the new tree and the old tree, and then minimizes the rerendering of the interface based on the differences.
  • In the differential calculation algorithm, React is able to know with relative accuracy which positions have changed and how, which ensures that it is updated on demand rather than re-rendering everything.

3. Triggers setState multiple times, how many times does Render execute?

  • Multiple setstates will be merged into one render, because setstates do not change the value of state immediately, but put it in a task queue, and eventually multiple setstates will be merged to update the page at once.
  • So we can call setState multiple times in our code, each time focusing on the current field.

How to modify data in state in React? Why is setState asynchronous?

  • Modify data via this.setstate (argument 1, argument 2)
  • This.setstate is an asynchronous function
    • Parameter 1: is the data to be modified is an object
    • Parameter 2: is a callback function that can be used to verify that the data was modified successfully, and can get the updated DOM structure equivalent to componentDidMount
  • The first argument in this.setState can be written as a function as well as an object! SetState ((prevState,prop)=>((prevState,prop)=>({}))

Why is it recommended to pass a callback to setState instead of an object?

  • Because updates to this.props and this.state may be asynchronous, you cannot rely on their values to calculate the next state

Why is setState asynchronous? (See 3)

  • DOM rendering is faster when state is executed in batches, which means that multiple setstates need to be combined during execution

What does React do after this.setState?

  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

5. How does the Virtual DOM work? (4 & 5 take one answer)

  • When data changes, such as setState, cause the component to be rerendered and the entire UI to be rerendered as a virtual DOM
  • Then collect the differences, namely diff the differences between the new virtual DOM and the old virtual DOM
  • Finally, the differences in the difference queue, such as adding nodes, deleting nodes, and moving nodes, are updated to the real DOM

5. Why does virtual DOM improve performance?

  • Virtual DOM is equivalent to adding a cache between JS and real DOM, and dom Diff algorithm is used to avoid unnecessary DOM operations, so as to improve performance.
  • The STRUCTURE of the DOM tree is represented as a JavaScript object structure
  • We then use this tree to build a real DOM tree, insert it into the document and rebuild a new object tree when the state changes.
  • The new tree is then compared to the old tree, and the differences between the two trees are recorded. The differences recorded in 2 are applied to the real DOM tree built in Step 1, and the view is updated.

6. The react principle of the diff

  • Break down the tree structure hierarchically, comparing only the elements at the same level.
  • Add a unique key attribute to each unit of the list structure to facilitate comparison.
  • React only matches components of the same class (class is the name of the component).
  • When the Component setState method is called, React marks it as dirty. At the end of each event loop, React checks that all dirty components are redrawn.
  • Select subtree rendering. Developers can override shouldComponentUpdate to improve diff performance.

7. What is the role of refs in React? (Detailed version)

  • Refs is a handle that React gives us to securely access a DOM element or a component instance.
  • Is used by the parent component to get the DOM element of the child component
  • We can add a ref attribute to an element and then accept a handle to that element in the DOM tree in the callback function, which is returned as the first argument to the callback function
class CustomForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}
Copy the code
  • The input field in the above code contains a ref attribute declaring a callback function that receives the DOM element corresponding to the input, which we bind to the this pointer for use in other class functions.
  • It is also worth mentioning that refs is not exclusive to class components; functional components can also use closures to temporarily store their values
 function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}
Copy the code

[Detailed and understandable version (recommended)]

1. Set the value of ref to an ordinary string

<button ref="myBtn"></button>
Copy the code
  • Define the ref attribute for the element, and then get the real DOM object via this.refs.mybtn
  • Define the ref property for the component, and then obtain the instance object of the component via this.refs.mybtn

2. Set ref to the arrow function

<button ref="{ (sl) => { this.myBtn = sl } }"></button>
Copy the code
  • Define the ref attribute for the element, and then get the real DOM object via this.mybtn
  • Define the ref property for the component, and then obtain the instance object of the component via this.mybtn

8. What are some ways to build components in React?

What’s the difference?

  • A function component looks like a function whose return value is a DOM structure, but behind it is the idea of stateless components.
  • In a function component, you can’t use State, nor can you use the lifecycle method of the component, which makes it a demonstrable component that receives Props, renders the DOM, and doesn’t care about any other logic
  • There is no this in the function component
  • Function components are easier to understand. When you see a function component, you know that its function is just to receive properties, render the page, it does no UI-independent logic, it’s just a pure function. Regardless of the complexity of the DOM structure it returns.

9. Event handler this points to a problem

How do event handlers pass arguments?

  • Arguments can be passed using bind
  • I give the event handler to the arrow function, and then I call the method inside the arrow function that I wanted to call at the beginning, when I’m a normal function.

[Attention!!]

  • If an event handler passes an extra argument, the event object is placed in the last one

10.

2. 100,000 whys

1. Why is it best not to use index as the key for loop rendering?

  • For example

Before the change, the value of the array is [1,2,3,4], and the corresponding index of the key is 0,1,2,3

  • So diff finds the value of key=0 in the array before the change is 1, and finds the value of key=0 in the array after the change is 4
  • Re-delete and update because the child elements are different
  • However, if you add a unique key, it looks like this:

Before the change, the array value is [1,2,3,4], and the key is the corresponding subscript: id0, id1, id2, id3

After the change, the array value is [4,3,2,1], and the index corresponding to the key is id3, id2, id1, id0

  • So diff finds the value of key= ID0 in the array before the change is 1, and the value of key= ID0 in the array after the change is also 1
  • Because the child elements are the same, you do not delete and update, only move, which improves performance

2. What is a state boost?

3. What are high-level components?

4. What are controlled and uncontrolled components?

What is a pure function?

6. What is the Context?

7. What is Portal in React?

8. What are react16 Error Boundaries?

3. Life Cycle (React17)

4. Communication

1. Father-son communication

2. Communication between sibling components

3. Communication across multi-layer components

4. Communication between any components

Article 5. The differences

1. How do you React to Vue?

2. What’s the difference between the state and the props?

3. What is the difference between Presentational Components and Container Components?

4. What is the difference between Element and Component in React?

5. What’s the difference between createElement and cloneElement in React?

6. Route

7. Story

(I)

9. HOC article (II)

10. The React hooks article (III)