React interview questions, everything! ! ! (Family bucket)

Create a react project command:

npx create-react-app my-app

Enter the folder:

cd my-app

Startup project:

npm start(开发模式下运行)
npm test(测试环境运行)
npm run build(打包为生产模式)

Display configuration file: irreversible, as long as it is displayed, there is no way to hide it back

npm run eject

 Why create subdirectories in src?

webpack only processes files in src. If you don't mention that css and html are placed in the src folder, webpack will not be able to find them .

react is a single page application

1. What is React?

JS library used to construct the user interface

2. What are the characteristics of React?

It is used for virtual DOM, componentized design mode, declarative code, one-way data flow, use jsx to describe information and other features

3. What is virtual DOM?

DOM for building virtual HTML

The virtual DOM can be regarded as a js object tree that simulates the DOM tree. E.g:

var element = {
    element: 'ul',
    props: {
        id:"ulist"
    },
    children: [
    { element: 'li', props: { id:"first" }, children: ['这是第一个List元素'] },
    { element: 'li', props: { id:"second" }, children: ['这是第二个List元素'] }
    ]
}

4. Why use virtual DOM?

As long as the traditional data changes, it will cause the DOM to re-render. The purpose of the virtual DOM is to accumulate all operations, calculate all the changes, and update the DOM once.

5. What is a componentized design pattern?

Reusable code can be extracted into components for common use (UI, methods, etc.) 

 

6. Declarative code (programming) thinking:

It’s what your purpose is and how you should do it, but it doesn’t specify how to do it.

Example: Go to the bar and tell the waiter that you want a cocktail, and the waiter gives you the prepared cocktail, and doesn’t say what the process is like

const toLowerCase = arr = arr.map(
    value => value.toLowerCase();
)

7. Are there other ways of programming?

Imperative programming

It is to describe how the code works, tell the computer to execute step by step, do what first and then do.

Example: Go to the bar to order a glass of wine and order the waiter

  • Remove a glass from the shelf
  • Put the glass in front of the wine barrel
  • Turn on the wine barrel switch until the wine glass is full
  • Pass the prepared cocktail to the customer
const toLowerCase = arr => {
    const res = [];
    for (let i = 0, len = arr.length; i < len; i++) {
        res.push(arr[i].toLowerCase());
    }
    return res;
}

8. Comparison of programmatic and imperative

  • Concise, easy to understand, conducive to the maintenance of large-scale project code
  • No need to use variables, avoid creating and modifying state 

9. What is a one-way data flow 

The data is mainly passed from the parent node to the child node (via props). If a prop of the parent changes, React will re-render all child nodes ( like waterfall water, flowing from top to bottom, this water is the data flow of the component) . )

// 父组件
import React, {Component} from 'react'
import Child from './Child'
class Parent extends Component{   
    // 初始化
    constructor(props){
        super(props)
        this.state = {
            message: '我是从父组件传过来的'
        }
    } 
    // 渲染
    render(){
        return(
            <div>
                <Son msg={this.state.message}/>
            </div>
        )
    }
}
export default Parent


// 子组件
import React, {Component} from 'react'
class Child extends Component{  
    // 初始化
    constructor(props){
        super(props)
    } 
    // 渲染
    render(){
        return(
            <div>
               {this.props.message}
            </div>
        )
    }
}
export default Child

10. What is JSX? JSX code to display content conversion process

JSX is the extended language of JS (jsx syntax = js syntax + xml (html) syntax)

JSX is an abbreviation of JavaScript XML, a grammatical extension of JavaScript, and is essentially a JavaScript object. JSX can describe UI information very well, but the browser cannot read it directly. JSX will be converted into JS syntax during the compilation process.

11. What are the main functions of react?

  • It uses virtual DOM, not real DOM
  • It follows one-way data flow

12.The advantages and disadvantages of react

advantage:

  • Improved application performance and development efficiency
  • Using JSX, the code is readable
  • React's componentWillUnmount life cycle can clear all related events and avoid memory leaks
  • It does not directly operate on the DOM, but introduces the concept of a virtual DOM, which is inserted between js and the real DOM, with good performance and fast speed 

Disadvantage: every time you  state change, the render function must generate a complete virtual DOM. Even if the  state change is small, the renderfunction will be calculated completely. If the  render function is very complicated, this process will waste a lot of computing resources in vain

https://blog.csdn.net/weixin_42052388/article/details/80902388

13. Comparison of the difference between the two frameworks of VUE and React 

Similarities:

  • Js library for creating UI
  • Light and convenient to use
  • Virtual DOM
  • Component-based architecture 

difference :

  • HTML template used by vue; React uses js
  • Vue has two-way binding syntax
  • Vue adds syntactic sugar computed and watch, etc. React needs to write its own logic to achieve
  • React uses jsx syntax
  • The overall idea of ​​react is programmatic, recommended componentization, data unchanged, one-way data flow; Vue data is variable, two-way binding, declarative writing

14. How React works  

React will create a virtual DOM. When the state of a component changes, React will first use the "diffing" algorithm to mark the changes in the virtual DOM. The second step is adjustment, which will update the DOM with the result of the diff.

15.Real DOM和Virtual DOM 

React does not directly manipulate the DOM, but implements the Virtual DOM. The component DOM is mapped to this virtual DOM. React implements the differ algorithm on the virtual DOM. When re-rendering the component, it will find the DO0M node to be changed through diff, and then update the modification to the actual DOM node of the browser. 

17. Why virtual DOM improves performance 

Virtual DOM is equivalent to adding a cache between JS and real DOM, using diff to reduce unnecessary operations, thereby improving performance. It is essentially a JS object.

  • The virtual DOM is a js object data structure that maps the real DOM
  • Use virtual DOM to avoid direct manipulation of real DOM and improve performance
  •  When the state is updated, the new virtual DOM is re-rendered, and the diff algorithm is used to compare the new and old DOM to update

18.Block React's default behavior  

e.preventDefault() e is a synthetic event provided by a third party

Note: You cannot use return

class App extends React.component{
constructor(props){
super(props);
this.state = {
}
}

hander(e){
e.preventDefault()
}
render(){
return <button onClick={ this.hander.bind(this) }>阻止事件</button>
}
}

19. Pass parameters to the event handler 

For example, delete the ID of the current row

<button onClick={(e) => this.delete(e,id)}>Delete Row<button>
<button onClick={this.delete.bind(this,id)}>Delete Row</button>

 20. What is the role of key in React? 

 Function (purpose): key is an auxiliary identifier used to track those elements in the list that have been modified, deleted or added. In the diff algorithm, the key is used to determine whether the element node is moved or a newly created element, reducing unnecessary repeated rendering of elements.

21. When rendering a list, what is the key?

Keys will help React to identify what itemshas changed, it is added or been removed. Keys should be assigned to the elements in the array to give a stable identification to the (DOM) element. The best way to choose a key is to use a string that uniquely identifies a list item. Many times you will use the data in IDs as keys, when you do not have a stable IDs are used for rendering items, you can use the project as rendering index entry key, but this approach is not recommended, if itemsyou can reorder, will leading to re-renderslow.

22. The diff algorithm in React 

The function of the diff algorithm is to calculate the changed part of the Virtual DOM, and then perform native DOM operations on this part without re-rendering the entire page.

https://www.cnblogs.com/yumingxing/p/9438457.html

The diff algorithm has 3 strategies:

  • tree diff: Cross-level movement operations of DOM nodes are particularly few and can be ignored.
  • Component diff: Two components with the same class generate similar data structures; two components with different classes generate different tree structures
  • element diff: For a group of child nodes at the same level, distinguished by a unique id

Principle of diff algorithm

  • Decompose the tree structure according to levels, and only compare elements at the same level
  • Add a unique key attribute to each unit of the list structure for easy comparison
  • React will only match components of the same class
  • In the merge operation, when the setState method of the component is called, React will mark it as dirty. At the end of each round of the event loop, React will check all components marked as dirty and re-render.
  • Selective subtree rendering. Developers can re-shouldComponentUpdate to improve diff performance.

 23. Element and Component in React

Element is a data structure that describes the content of the courseware on the screen, and is a bid for UI objects

Component is a function or class that can accept parameter input and return a ReactElement

24.props and state (what is the difference between state (state) and properties (props) (of the component))

  • State is a data structure, which will be sent and changed as the event goes on, and can only be changed using setState
  • Props are the properties of the component, passed from the parent component to the child component, props cannot be changed 

The state is local, except for the component in which it is located, no other components can be accessed

  • Stateless components: components without state set (stateless components are constructed through functional declarations, a function is a component)
  • Stateful component: the component with state set (stateful component is constructed by component, a subclass is a component)

25. React can declare components in two ways. What is the difference between them and which one would you choose under what circumstances? ( What are the ways to build components in React)  

  •  Function component: the first letter should be capitalized, and the react element needs to be returned
  • Class Components: Capitalize the first letter, use the render method, and return the react element
// 函数组件
function Welcome(props){
return (
<h1>hello world</h1>
)
}


// 类组件
class Welcome extends React.Component{
        render(){
            return (
            <div>11</div>
        )
    }
}

the difference:

  • The functional component seems to be just a function whose return value is the DOM structure, but behind it is the idea of ​​stateless components
  • In functional components, you cannot use State, nor can you use the life cycle method of the component, which determines that functional components are all expandable components, receiving props, rendering DOM, and not paying attention to other logic
  • There is no this in the function component
  • Function components are easier to understand. When you see a functional component, you know that its function is only to receive properties and render the page. It does not perform logic processing that has nothing to do with the UI. It is just a pure function. Don’t care how complex the DOM structure it returns

26. What are the stages of the React component life cycle?

There are three different stages in the life cycle of React components:

  1. Initial rendering stage: This is the stage where the component is about to begin its life journey and enter the DOM.
  2. Update stage: Once the component is added to the DOM, it can only be updated and re-rendered when the prop or state changes. These only happen at this stage.
  3. Uninstallation phase: This is the final phase of the component life cycle, the component is destroyed and removed from the DOM.

27. Briefly talk about the life cycle (point out the difference in (component) life cycle methods)

  • constuctor: initialize props and state in the constructor
  • componentWillMount--execute before component rendering, make the final modification to the state
  • render: rendering
  • componentDidMount-- execute after component rendering
  • componentWillReceiveProps - This periodic function acts on the state transition caused by a specific prop change
  • shouldComponentUpdate - Used for performance optimization, returns true or false according to specific conditions. If you want to update the component, please return true  otherwise return  false . By default, it returns false.
  • componentWillUpdate - The data is executed before the change
  • componentDidUpdate - Called immediately after rendering occurs
  • componentWillUnmount - Called after the component is unloaded from the DOM. Used to clean up memory space

28. What is one-way data flow and state improvement

  • One-way data flow: From top to bottom, the parent component flows state data to the child component, and the child component gets the value through props (like the water of a waterfall, flows from top to bottom, this water is the data flow of the component)
  • State promotion: data interaction between components (many sub-components want to use this state, raise this state to the top, who uses props to whom)

Example: If both components need to use the other's state, then state promotion can be used at this time. The specific method is to write the state of the two child components to their parent component, and then the parent component transfers the state to the props of the child component, so that the child component is also equivalent to state.

Parent component

import React from "react"
import Child1 from "./child1"
import Child2 from "./child2"

export default class Parent extends React.Component {

    constructor() {
        super()
        this.state = {
            money: 1
        }
    }

    changeHander(e){
        this.setState({
            money: e.target.value
        })
    }
    render() {
        return (
            <div>
                <input type="text" value={ this.state.money } onChange={this.changeHander.bind(this)} />
                <p>Parent</p>
                人民比: <Child1 money={this.state.money} />
                美金: <Child2 money={this.state.money} />
            </div>
        )
    }
}

 Subcomponent 1

import React from "react"

export default class Child1 extends React.Component{

    constructor(){
        super()
        this.state = {
            input1: 0
        }
    }

    componentDidMount(){
        this.setState({
            input1: this.props.money
        })
    }

    changeHander(e) {
        this.setState({
             input1: e.target.value
        })
    }

    render() {
        return(
            <div>
                 { this.props.money }
               <input type="text" value={ this.state.input1 } onChange={ this.changeHander.bind(this) }/>
            </div>
        )
    }
}

 Subcomponent 2

import React from "react"

export default class Child2 extends React.Component{

    constructor(){
        super();
        this.state = {
            input2: 1
        }
    }

    componentDidMount(){
        this.setState({
            input2: this.props.money * 7
        })
    }

    changeHander(e) {
        this.setState({
             input2: e.target.value
        })
    }
    render() {
        return(
            <div>
                { this.props.money * 7}
               <input type="text" value={ this.state.input2 } onChange={ this.changeHander.bind(this) }/>
            </div>
        )
    }
}

29. What happened after calling setState

setState will update the state

The incoming parameter object is merged with the current state of the component, and then the so-called reconciliation process is triggered. After the reconciliation process, according to the new state, the React element will rebuild the virtual DOM, perform the diff algorithm to compare the difference between the new and the old virtual DOM tree, and update the view. Instead of rendering all.

The task queue mechanism used by setState will not be executed immediately, but will be added to the queue, and will be executed once in the next event loop

30. Why is it recommended that the parameter passed to setState is a callback (callback function) rather than an object (don’t understand-don’t memorize it first)

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

31. About this binding == component binding click event

// bind
// 1
<button onClick={this.handleClick.bind(this)}>hello<button/>
// 2
clicked(param,event){
    console.log(param) //hello world
    console.log(event.target.value) //按钮
}
render(){
    return (
        <React.Fragment>
            <button value="按钮" onClick={this.clicked.bind(this,"hello world")}>点击</button>
        </React.Fragment>
    )
}


// 2.在构造函数中默认绑定this(推荐)
this.handleClick = this.handleClick.bind(this)

// 3.使用箭头函数来处理,handleClick点击事件的方法
<button onClick={(e) => this.handleClick(e)}>Click me</button>

32. The role of the second parameter of setState (don’t understand-don’t memorize)

This function will be called when the setState function call is completed and the component starts to re-render. We can use this function to monitor whether the rendering is complete

(In the constructor) what is the purpose of calling super(props)

 Before super() is called, subclasses cannot use this. In ES5, subclasses must call super() in the constructor. Cause props passed to super () is able to facilitate (in the subclass) constructorAccessthis.props

33. What is React routing?

Router is used to define multiple routes. When a user defines a specific URL, if this URL matches the path of any "route" defined in the Router, the user will be redirected to that specific route.

import React from 'react';
import { Switch, Route, BrowserRouter } from 'react-router-dom';
import Home from './views/Home'

export default class App extends React.Component{
    // 初始化
    constructor(props){
        super(props);
        this.state = {}
    }
    // 渲染
    render(){
        return(
           <BrowserRouter>
               <Switch>
                   <Route component={Home} path="/" />
               </Switch>
           </BrowserRouter>
        )
    }
}

 

Guess you like

Origin blog.csdn.net/qq_40055200/article/details/108549121