1. Differences between elements and components in React

At that time, I just learned React, so I didn’t know what the interviewer was talking about. Now I know, it’s virtual DOM.

React element

It is the smallest basic unit in React, and we can easily create a React element using JSX syntax:

const element = <div className="element">I'm element</div>
Copy the code

React elements are not real DOM elements. They are just plain objects in JS, so there is no way to directly call the DOM native API. The JSX translated object above looks something like this:


{
    _context: Object,
    _owner: null,
    key: null,
    props: {
    className: 'element'And the children:'I'm element' }, ref: null, type: "div" }Copy the code

In addition to using JSX syntax, we can also build React elements using React.createElement() and React.cloneElement().

The React components

There are three ways to build components in React. React.createclass (), ES6 class, and stateless functions.

1, the React. CreateClass ()

var Greeting = React.createClass({
  render: function() {
    return<h1>Hello, {this.props.name}</h1>; }});Copy the code

2, ES6 class

class Greeting extends React.Component{
  render: function() {
    return<h1>Hello, {this.props.name}</h1>; }};Copy the code

3. Stateless functions

A stateless function is a stateless component that is built using functions. A stateless component passes props and context. It has no state and no lifecycle methods other than render().

function Greeting (props) {
  return <h1>Hello, {props.name}</h1>;
}
Copy the code

4, PureComponent

PureComponent and Component are basically identical except that they provide you with a shouldComponentUpdate method with a shallow comparison.

The difference between elements and components

Components are made up of elements. Element data structures are ordinary objects, while component data structures are classes or pure functions.

2. What is the use of Forwarding Refs

Is used by the parent component to retrieve the DOM elements of the child component. Why is this API available

Class Child extends React.Com (props){constructor(props){super(props); }render() {return<input />}} // 错 句 : class Father extends React.Com {constructor(props){super(props); this.myRef=React.createRef(); }componentDidMount(){
    console.log(this.myRef.current);
  }
  render() {return <Child ref={this.myRef}/>
  }
}
Copy the code

This.myref. current is the Child component, which is an object. If the react.forwardref is used, it’s as follows

Const Child = React. ((props, ref) => (<input ref={ref} />)); Class Father extends React.Com {constructor(props) {super(props); this.myRef = React.createRef(); }componentDidMount() {
        console.log(this.myRef.current);
    }
    render() {
        return <Child ref={this.myRef} />
    }
}
Copy the code

The parent’s this.myref. current value is the INPUT DOM element

3. How does the Virtual DOM work?

  • 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

4. Do you know the Fiber architecture

Note: the answers refer to the article of Situ Zhengmei

4.1. What advantages does the Fiber architecture have over previous recursive update components

  • The reason is that recursively updating components takes a long time on the JS call stack.
  • Because the browser is single-threaded, it pulls together GUI rendering, event handling, JS execution, and so on. Only after it’s done can we move on to the next thing. Given enough time, the browser will JIT optimize our code and do hot code optimization.
  • The Fiber architecture takes advantage of this principle to perform component rendering in segments and improve it so that browsers have time to optimize JS code and fix reflow!

4.1. Since you said that Fiber will render components in sections, after the first rendering, how do you know which component to render next?

  • Fiber node has three attributes: return, Child and Sibling, which respectively correspond to the parent node, the first child and its sibling on the right. Having them is enough to turn a tree into a linked list and realize deeply optimized traversal.

4.2 How to determine the number of updates

  • React16 needs to convert the virtual DOM to Fiber nodes by first defining a time period and then updating as many FiberNodes as can be converted during that time period.
  • So we need to divide our update logic into two phases. The first phase is to convert the virtual DOM to a Fiber, and the Fiber to a component instance or a real DOM (do not insert the DOM tree, insert the DOM tree will reflow). The conversion of Fiber to the latter two will obviously take time, and you need to calculate how much time is left.
  • For example, we can record the time when we started updating the view var now = new Date -0. If our update attempt takes 100 milliseconds to customize, then define the end time as var deadline = new Date + 100, so each time we update a portion of the view, If the deadline is not exceeded, the view will be updated. If the deadline is exceeded, the view will enter the next update phase

4.3 How Can I Schedule time Smoothly

  • Using the browser’s built-in API – requestIdleCallback,
  • Its first argument is a callback. The callback has a parameter object that has a timeRemaining method equivalent to new date-deadline and is a high-precision data that is more accurate than milliseconds
  • Because of browser compatibility issues, the React team implemented requestIdleCallback itself

What is the new lifecycle of 4.4 Fiber

When creating

  • constructor ->
  • GetDerivedStateFromProps (nextProps, prevState, note that this does not refer to the component instance)->
  • render ->
  • componentDidMount

update

  • GetDerivedStateFromProps (props: props, props, prevState) ->
  • ShouldComponentUpdate (nextProps, nextState)->
  • render->
  • GetSnapsshotBeforeUpdate (replace componentWillUpdate)
  • ComponentDidUpdate (prevProps, prevState, snapshot)

5. What are controlled and uncontrolled components

  • For status-controlled components, you must have an onChange method, otherwise you cannot use the controlled components that can be assigned to default values (the official recommendation is to use controlled components) for bidirectional data binding
class Input extends Component{
    constructor(){
        super();
        this.state = {val:'100'}} handleChange = (e) =>{//e is the event sourcelet val = e.target.value;
        this.setState({val});
    };
    render() {return (<div>
            <input type="text" value={this.state.val} onChange={this.handleChange}/>
            {this.state.val}
        </div>)
    }
}
Copy the code
  • Uncontrolled means THAT I can manipulate the real DOM through the REF without setting its state property
class Sum extends Component{
    constructor(){
        super();
        this.state =  {result:' '}} // The dom element can be obtained by this. Refs handleChange = () =>{let result = this.refs.a.value + this.b.value;
        this.setState({result});
    };
    render() {return (
            <div onChange={this.handleChange}>
                <input type="number" ref="a"/> {/*x represents the real DOM, with elements mounted on the current instance */} <inputtype="number" ref={(x)=>{
                    this.b = x;
                }}/>
                {this.state.result}
            </div>
        )
    }
}
Copy the code

6. What is state improvement

When using React, you often encounter situations where several components need to share state data. In this case, it is best to promote the shared state to their most recent parent. So let’s see how that works.

import React from 'react'
class Child_1 extends React.Component{
    constructor(props){
        super(props)
    }
    render() {return (
            <div>
                <h1>{this.props.value+2}</h1>
            </div> 
        )
    }
}
class Child_2 extends React.Component{
    constructor(props){
        super(props)
    }
    render() {return (
            <div>
                <h1>{this.props.value+1}</h1>
            </div> 
        )
    }
}
class Three extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            txt:"Cool"
        }
        this.handleChange = this.handleChange.bind(this)
    }
    handleChange(e){
        this.setState({
            txt:e.target.value
        })
    }
    render() {return (
            <div>
                <input type="text"value={this.state.txt} onChange={this.handleChange}/> <p>{this.state.txt}</p> <Child_1 value={this.state.txt}/> <Child_2  value={this.state.txt}/> </div> ) } }export default Three
Copy the code

7. What is a high-level component

A higher-order component is not a component, but an enhancer. You can enter a meta-component and return a new enhancer

  • In my opinion, the property Proxy is to extract the common data and methods to the parent component, and the child component is only responsible for rendering the data. It is similar to the template pattern in design pattern, so that the component can be reused more easily
function proxyHoc(WrappedComponent) {
	return class extends React.Component {
		render() {
			const newProps = {
				count: 1
			}
			return<WrappedComponent {... this.props} {... newProps} /> } } }Copy the code
  • Reverse inheritance
const MyContainer = (WrappedComponent)=>{
    return class extends WrappedComponent {
        render() {returnsuper.render(); }}}Copy the code

What is the Context

Context provides a method to pass data through the component tree, avoiding the need to manually pass props at each level.

  • Usage: Define the getChildContext method on the parent component to return an object that can then be retrieved by its children via the this.context property
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class Header extends Component{
    render() {
        return (
            <div>
                <Title/>
            </div>
        )
    }
}
class Title extends Component{
    static contextTypes={
        color:PropTypes.string
    }
    render() {
        return (
            <div style={{color:this.context.color}}>
                Title
            </div>
        )
    }
}
class Main extends Component{
    render() {
        return (
            <div>
                <Content>
                </Content>
            </div>
        )
    }
}
class Content extends Component{
    static contextTypes={
        color: PropTypes.string,
        changeColor:PropTypes.func
    }
    render() {
        return (
            <div style={{color:this.context.color}}>
                Content
                <button onClick={()=>this.context.changeColor('green'</button> <button onClick={()=> this.context.changecolor ()'orange'</button> </div>)}} Class Page extends Component{constructor() {
        super();
        this.state={color:'red'};
    }
    static childContextTypes={
        color: PropTypes.string,
        changeColor:PropTypes.func
    }
    getChildContext() {
        return {
            color: this.state.color,
            changeColor:(color)=>{
                this.setState({color})
            }
        }
    }
    render() {
        return (
            <div>
                <Header/>
                <Main/>
            </div>
        )
    }
}
ReactDOM.render(<Page/>,document.querySelector('#root'));
Copy the code

9. What is Portal in React?

Portals provide a great way to render a child node to a DOM node other than the parent component.

ReactDOM.createPortal(child, container)
Copy the code

The first argument (child) is any renderable React child element, such as an element, string, or fragment. The second parameter (Container) is a DOM element.

10. What are the Error Boundaries of React16

JavaScript errors in part of the UI should not break the entire application. To address this issue for React users, React 16 introduces a new concept called “Error Boundaries.”

import React from 'react';
import ReactDOM from 'react-dom';
class ErrorBoundary extends React.Component{
    constructor(props) {
        super(props);
        this.state={hasError:false};
    }
    componentDidCatch(err,info) {
        this.setState({hasError: true});
    }
    render() {
        if (this.state.hasError) {
            return <h1>Something Went Wrong</h1>
        }
        return this.props.children;
    }
}

class Page extends React.Component{
    render() {
        return (
            <ErrorBoundary>
                <Clock/>
            </ErrorBoundary>
        )
    }
}
class Clock extends React.Component{
    render() {
        return (
            <div>hello{null.toString()}</div>
        )
    }
}

ReactDOM.render(<Page/>,document.querySelector('#root'));
Copy the code

How do I use innerHTML in React

Add a dangerouslySetInnerHTML attribute and pass in an object attribute named _html

function Component(props){
    return <div dangerouslySetInnerHTML={{_html:'< span > hello < / span >'}}>
            </div>
}
Copy the code

What are the reconciliation and Commit phases of React16

  • The reconciliation phase includes the main work of diff calculation for current tree and new tree to find out the changes. Traversal, comparison, and so on can be interrupted, and then come back after a short break.
  • The COMMIT phase is a series of DOM operations that apply the changes obtained in the previous phase to the real DOM tree. Not only is the DOM state more complex to maintain, but the user experience can be affected by continuing after an interruption. In common application scenarios, the time of this phase is shorter than that of diFF calculation.

13. Tell us a little about the react event mechanism

  • React does not bind the Click time to the DOM when the user is adding onClick functions.
  • Instead, React listens for all supported events at the document. When an event occurs and bubbles to the document, React encapsulates the event content into a middle layer called SyntheticEvent.
  • So when the event is triggered, the dispatchEvent function will specify the function to execute.

14. 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,3Copy the code
  • 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
  • But if you add a unique key, it looks like this
Before the change, the value of the array is [1,2,3,4], and the corresponding subscript of the key is id0, id1, id2, and id3. After the change, the value of the array is [4,3,2,1], and the corresponding subscript of the key is id3, id2, id1, id0Copy the code
  • 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