React common interview questions

1. React life cycle function

  • Initialization phase:

    • getDefaultProps: Get the default properties of the instance
    • getInitialState: Get the initialization state of each instance
    • componentWillMount: The component is about to be loaded and rendered on the page
    • render: The component generates a virtual DOM node here
    • componentDidMount: After the component is actually loaded
  • Running status:

    • componentWillReceiveProps: Called when the component is about to receive properties
    • shouldComponentUpdate: When the component receives new properties or new states (can return false, do not update after receiving data, prevent render calls, and subsequent functions will not be executed)
    • componentWillUpdate: The component is about to be updated and cannot modify properties and states
    • render: component redrawing
    • componentDidUpdate: The component has been updated
  • Destruction phase:

    • componentWillUnmount: The component is about to be destroyed
  • Error message stage:

    • componentDidCatch: after component error message

2. Which periodic function is the performance optimization of react?

        A more optimized dom diff algorithm can be written in the shouldComponentUpdate method, which can greatly improve performance.

3. What is the difference between (component) state (state) and properties (props)

  • State is a data structure used for the default value of the data required when the component is mounted. State may mutate over time, but mostly as a result of user event behavior.
  • Props (short for properties) is the configuration of the component. Props are passed from parent components to child components, and as far as child components are concerned, props are immutable. A component cannot change its own props, but it can put the props of its subcomponents together (unified management). Props aren't just data either - callbacks can be passed in props too.

4. Why is it recommended that the parameter passed to setState be a callback instead of an object

Since this.props and this.state may be updated asynchronously, their values ​​cannot be relied upon to calculate the next state.

5. What is the importance of key in React?
       

           A key is used to identify a unique Virtual DOM element and its corresponding data that drives the UI. They help React optimize rendering by recycling all elements currently in the DOM. These keys must be unique numbers or strings, React just reorders the elements instead of re-rendering them. This can improve application performance.

Six, the role of the second parameter of setState

       Because setState is an asynchronous process, the value in state cannot be changed immediately after setState is executed. If you need to monitor state data changes, setState provides a second parameter, which is used to monitor data changes in the state, and when the data changes are completed, call the callback function.

Seven, the order of life cycle calls in the running phase

        componentWillReceiveProps–>shouldComponentUpdate --> componentWillupdate --> componentDidUpdate

8. How to modify the data in state in react? Is this.setState synchronous or asynchronous? What does the second parameter in this.setState do? Why is it asynchronous?

  1. Modify the data in the state through this.setState;
  2. this.setState is asynchronous;
  3. Why is it asynchronous, one state can be executed in batches, that is to say, when multiple setStates are executed at the same time, they will be merged to improve the rendering efficiency of DOM;
  4. When is this.setState synchronous? Events bound by native js, setTimeout/setInterval, etc. (when not controlled by the react mechanism)
  5. this.setState itself is actually a synchronous one. Asynchronous is not because of its own operating mechanism or code, but because the call sequence of its synthetic event and hook function is before the update, which makes it impossible to get the updated value immediately in the function , forming the so-called asynchronous, you can get the updated result through the callback in the second parameter;

Nine, react performance optimization scheme

  (1) Rewrite shouldComponentUpdate to avoid unnecessary dom operations.
  (2) Use the production version of react.js.
  (3) Use key to help React recognize the minimal change of all child components in the list.

10. The difference between vue and react

    1. React is strictly aimed at the view layer of the MVC mode, while Vue is the MVVM mode.
    2. The way to operate dom is different. Vue uses instructions to operate dom, and react operates through js.
    3. Data binding is different. Vue implements two-way binding, while react's data flow is one-way.
    4. The state in react cannot be changed directly, you need to use setState to change it. The state in vue is not necessary, and the data is mainly managed by the data attribute in the vue object.

Eleven, the difference between sass and less

    1. The symbols used to define variables are different. Less uses @, and sass uses $.
    2. The scope of variables is different. When less is defined globally, it acts globally. When defined in a code block, it acts on the entire code block. Sass, on the other hand, only has a global scope.
    3. The compilation environment is different, less is compiled in the developer environment, and sass is compiled in the server environment

12. Component value passing in react

  • Parent components communicate to child components: props
  • Child component communicates with parent component: callback function/custom event
  • Cross-level component communication: Layer-by-layer components pass props/context
  • Communication between components without nested relationships: custom events

When communicating between components, mainly look at the specific needs of the business and choose the most suitable one; when the business logic is complicated to a certain extent, you can consider introducing Mobx , Redux and other state management tools

Thirteen. What is the difference between arrow functions and ordinary functions in Es6?

    1. Ordinary function declarations are the highest in variable promotion. Arrow functions do not have function promotion.
    2. Arrow functions do not have this and arguments.
    3. Arrow functions cannot be used as constructors, cannot be new, and have no property.
    4. There are only call and apply methods parameter, no scope

14. What are the methods of routing parameters in react?

  • Dynamic routing:

           When routing jumps: path + key form;

           Receive: this.props.match.params;

  • query pass value:

            When defining a route: same as normal;

            When routing jumps: use string splicing;

             Receive: this.props.location.search

  • Object pass value:

           When defining a route: same as normal;

          When routing jumps: use objects, which contain objects that define paths and objects that pass parameters;

          Receive: this.props.history.query

  • Programmatic navigation:

          this.props.history.push({path part}, {parameter part})

Note: When using object passing by value and programmatic navigation passing by value, if the page is refreshed, the passed value will disappear;

Fifteen, Redux implementation principle analysis

    ReduxIt is called storing the entire application state in one place store, which stores a state tree store tree, and components can dispatch ( dispatch) behavior ( action) to store, instead of directly notifying other components, the components internally refresh their own views by subscribing storeto the statestate

 

16. In the mobile application implemented by React, if there is a freeze, what optimization solutions can be considered

  • Add shouldComponentUpdatea hook to propscompare the old and new, and prevent the update if the values ​​are the same, avoid unnecessary rendering, or use PureReactComponentan alternative , which has encapsulated the shallow comparison logic ComponentinsideshouldComponentUpdate
  • For lists or other nodes with the same structure, add a unique attribute to each item keyto facilitate Reactthe diffreuse of the node in the algorithm and reduce the creation and deletion of nodes
  • renderReduce similar writing in the function onClick={() => {doSomething()}}. A new function will be created every time the render function is called. Even if the content does not change, it will cause unnecessary re-rendering of the node. It is recommended to save the function in the member object of the component, so that will only be created once
  • If the component propsneeds to go through a series of calculations to get the final result, you can consider using reselectthe library to cache the result. If the props value does not change, the result will be taken directly from the cache to avoid high calculation costs
  • webpack-bundle-analyzerAnalyze the dependent packages of the current page, whether there is unreasonableness, if so, find the optimization point and optimize it

17. HOC (Higher Order Component)

Brief description:

  • Higher-order components are not components, but enhanced functions, which can input a meta-component and return a new enhanced component;
  • The main functions of high-level components are code reuse, operation status and parameters;

usage:

  • Props Proxy: Returns a component that enhances functions based on the wrapped component;
  1. Default parameters: You can wrap a layer of default parameters for components;
  2. Extract state: The state in the wrapped component can be dependent on the outer layer through props, for example, to convert the controlled component:

Application scenario:

Authority control, through abstract logic, uniformly judges the authority of the page, and renders the page according to different conditions:

Guess you like

Origin blog.csdn.net/ShIcily/article/details/115536607