Summary of common react interview questions (suitable for intermediate front-end)

From https://segmentfault.com/a/1190000016885832?utm_source=tag-newest#item-11

What is the role of keys in React?

Keys are secondary identifiers used by React to track which elements in a list have been modified, added, or removed.

render () {
  return (
    <ul>
      {this.state.todoItems.map(({item, key}) => {
        return <li key={key}>{item}</li>
      })}
    </ul>
  )
}

In the development process, we need to ensure that the key of an element is unique among its sibling elements. In the React Diff algorithm, React uses the key value of an element to determine whether the element is newly created or moved, thereby reducing unnecessary re-rendering of elements. In addition, React also needs to use the Key value to determine the association between the element and the local state, so we must not ignore the importance of Key in the conversion function.

What happened after calling setState?

After calling the setState function in the code, React will merge the incoming parameter object with the current state of the component, and then trigger the so-called reconciliation process (Reconciliation). After the reconciliation process, React will construct the React element tree according to the new state in a relatively efficient manner and set about re-rendering the entire UI interface. After React gets the element tree, React will automatically calculate the difference between the new tree and the old tree, and then minimize and re-render the interface according to the difference. In the difference calculation algorithm, React can relatively accurately know which positions have changed and how they should be changed, which ensures that they are updated on demand, rather than re-rendering all.

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 mounted
  • Running state:

    • componentWillReceiveProps: Called when the component is about to receive properties
    • shouldComponentUpdate: When a component receives a new property or a new state (can return false, it does not update after receiving the data, prevents the render call, and the following functions will not be continued)
    • componentWillUpdate: the component is about to be updated and the attributes and state cannot be modified
    • render: component repaint
    • componentDidUpdate: the component has been updated
  • Destruction phase:

    • componentWillUnmount: The component is about to be destroyed

What shouldComponentUpdate do, (which periodic function is React performance optimization for?)

shouldComponentUpdate This method is used to determine whether the render method needs to be called to redraw the dom. Because the description of dom is very costly, if we can write a more optimized dom diff algorithm in the shouldComponentUpdate method, we can greatly improve performance.

Reference react performance optimization -sf

Why does virtual dom improve performance? (Required)

Virtual dom is equivalent to adding a cache between js and real dom, using the dom diff algorithm to avoid unnecessary dom operations, thereby improving performance.

Use JavaScript object structure to represent the structure of the DOM tree; then use this tree to build a real DOM tree, insert it into the document and when the state changes, reconstruct a new object tree. Then compare the new tree with the old tree, record the difference between the two trees, apply the difference recorded in 2 to the real DOM tree constructed in step 1, and the view is updated.

Reference  how to understand a virtual DOM? -Zhihu

The principle of react diff (often tested, must be tested by major manufacturers)

  • Decompose the tree structure according to hierarchy and compare only elements of the same level.
  • Add a unique key attribute to each cell of the list structure for easy comparison.
  • React will only match components of the same class (class here refers to the name of the component)
  • In the merge operation, when the setState method of the component is called, React marks it as dirty. At the end of each event loop, React checks all components marked dirty for redrawing.
  • Selective subtree rendering. Developers can rewrite shouldComponentUpdate to improve the performance of diff.

Reference: React's diff algorithm

What is the role of refs in React?

Refs are the handles provided by React for secure access to DOM elements or a component instance. We can add a ref attribute to the element and then accept the handle of the element in the DOM tree in the callback function, which will be returned as the first parameter of 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>
    )
  }
}

The input field in the above code contains a ref attribute. The callback function declared by this attribute will receive the DOM element corresponding to the input. We bind it to this pointer for use in other class functions. It is also worth mentioning that refs are 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>
  )
}

If you create a Twitter element similar to the following, what does its related class definition look like?

<Twitter username='tylermcginnis33'>
  {(user) => user === null
    ? <Loading />
    : <Badge info={user} />}
</Twitter>
import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'
// fetchUser take in a username returns a promise
// which will resolve with that username's data.
class Twitter extends Component {
  // finish this
}

If you are not familiar with the Render Callback Pattern, this code may look a bit strange. In this mode, the component will receive a function as its child component, and then call it with props.children in the rendering function:

import React, { Component, PropTypes } from 'react'
import fetchUser from 'twitter'
class Twitter extends Component {
  state = {
    user: null,
  }
  static propTypes = {
    username: PropTypes.string.isRequired,
  }
  componentDidMount () {
    fetchUser(this.props.username)
      .then((user) => this.setState({user}))
  }
  render () {
    return this.props.children(this.state.user)
  }
}

The advantage of this model is that it decouples the parent component from the child component. The parent component can directly access the internal state of the child component without passing through Props, so that the parent component can more easily control the UI interface displayed by the child component. For example, the product manager asked us to replace the Badge that we originally displayed with the Profile. We can easily modify the callback function:

<Twitter username='tylermcginnis33'>
  {(user) => user === null
    ? <Loading />
    : <Profile info={user} />}
</Twitter>

Show the difference between the Presentational component and the Container component

  • The presentation component cares about what the component looks like. The display specifically accepts data and callbacks through props, and almost never has its own state, but when the display component has its own state, it usually only cares about the UI state rather than the state of the data.
  • Container components are more concerned with how components work. The container component will provide data and behavior for the display component or other container components. They will call Flux actions and provide it as a callback to the display component. Container components are often stateful because they are data sources (of other components).

What is the difference between Class component and Functional component

  • Class components not only allow you to use more additional functions, such as the component's own state and life cycle hooks, but also enable the component to directly access the store and maintain state
  • When a component only receives props and renders the component itself to the page, the component is a 'stateless component', and a pure function can be used to create such a component. Such components are also called dumb components or display components

What is the difference between (component) 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 most of the time as a result of user event behavior.
  • Props (short for properties) is the configuration of components. Props are passed from the parent component to the child component, and as far as the child component is concerned, props are immutable. Components cannot change their own props, but they can put together the props of their subcomponents (unified management). Props are not just data-callback functions can also be passed through props.

What is a controlled component

In HTML, similar  <input><textarea> and  <select> such form elements maintain their own state and are updated based on user input. When the user submits the form, the value of the aforementioned element will be sent along with the form. But in React, it will be a bit different. The component that contains the form element will track the input value in the state, and each time the callback function is called, such as onChange will update the state and re-render the component. An input form element whose value is controlled by React in this way, such an element is called a "controlled element".

What is a higher order component?

A higher-order component is a function that takes a component as a parameter and returns a new component. HOC allows you to reuse code, logic, and bootstrap abstractions. Perhaps the most common is Redux's connect function. In addition to simple sharing tool libraries and simple combinations, the best way for HOC is to share the behavior between React components. If you find that you write a lot of code in different places to do the same thing, you should consider refactoring the code into a reusable HOC.

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

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

Besides binding this in the constructor, is there any other way?

You can use property initializers to properly bind callbacks, and create-react-app is also supported by default. You can use arrow functions in callbacks, but the problem is that a new callback is created each time the component is rendered.

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

Subclasses cannot use this before super () is called. In ES2015, subclasses must call super () in the constructor. The reason for passing props to super () is to make it easier (in subclasses) to access this.props in the constructor.

Where should React components initiate Ajax requests

In React components, network requests should be initiated in componentDidMount. This method will be executed when the component is first "mounted" (added to the DOM) and will only be executed once during the component's life cycle. More importantly, you cannot guarantee that the Ajax request has been completed before the component is mounted. If so, it means that you will try to call setState on an unmounted component, which will not work. Initiating a network request in componentDidMount will ensure that there is a component that can be updated.

Describe how events are handled in React.

To address cross-browser compatibility issues, the event handler in your React will pass an instance of SyntheticEvent, which is a cross-browser wrapper for React's browser-native events.

These SyntheticEvents have the same interface as the native events you are used to, except that they are compatible in all browsers. Interestingly, React does not actually attach events to the child nodes themselves. React will use a single event listener to listen to all events at the top level. This is good for performance, which also means that React does not need to worry about tracking event listeners when updating the DOM.

What is the difference between createElement and cloneElement?

React.createElement (): The JSX syntax uses React.createElement () to construct React elements. It accepts three parameters, the first parameter can be a label name. Such as div, span, or React components. The second parameter is the incoming attribute. The third and subsequent parameters are all subcomponents of the component.

React.createElement(
    type,
    [props],
    [...children]
)

React.cloneElement () is similar to React.createElement (), except that the first parameter it passes is a React element, not a tag name or component. The newly added attributes will be merged into the original attributes and passed into the returned new element, and the child element trophy will be replaced.

React.cloneElement(
  element,
  [props],
  [...children]
)

There are three ways to build components in React

React.createClass (), ES6 class and stateless functions.

React component division business component technology component?

  • Components are usually divided into UI components and container components according to their responsibilities.
  • The UI component is responsible for UI presentation, and the container component is responsible for managing data and logic.
  • The two are connected by the Connect method provided by React-Redux.

Brief description of flux thought

The biggest feature of Flux is the "one-way flow" of data.

  1. User access to View
  2. View issues user actions
  3. Dispatcher receives the Action and asks the Store to update accordingly
  4. After the Store is updated, a "change" event is issued
  5. After View receives the "change" event, it updates the page

What scaffolding has been used in the React project (this question is an open topic)

creat-react-app Yeoman 等

Do you understand redux?

  • Redux is an application data flow framework, which mainly solves the problem of state sharing between components. The principle is centralized management. There are three main methods: action, store, reducer, and the workflow is that the view calls the store's dispatch to receive the action and the incoming store. , Reducer performs state operation, view obtains the latest data through the getState provided by the store, flux is also used for data operation, there are four components action, dispatch, view, store, the workflow is that the view sends an action and the dispatcher receives Action, let the store update the data. After the update is complete, the store issues a change, and the view accepts the change to update the view. Redux is very similar to Flux. The main difference is that Flux has multiple stores that can change the state of the application. In Flux, the dispatcher is used to pass data to the registered callback event, but in redux, only one store with an updateable state can be defined. Redux combines the store and the Dispatcher. The structure is simpler and clearer
  • The new state is added, the state management is more clear, through redux, the process is more standardized, the amount of manual coding is reduced, and the coding efficiency is improved. At the same time, when the data is updated, sometimes the components are not needed, but they also need to be redrawn effectiveness. In general, we only use them when constructing complex projects with multiple interactions and multiple data streams.

What are the disadvantages of redux

  • The data required by a component must be passed by the parent component, not directly from the store like in flux.
  • When the data related to a component is updated, even if the parent component does not need to use the component, the parent component will still be re-rendered, which may have an effect on efficiency, or a complex shouldComponentUpdate needs to be written to judge.

Guess you like

Origin www.cnblogs.com/passkey/p/12735123.html