React front-end interview questions (unfinished version)

Write the directory title here

1. How to avoid life cycle pitfalls

Insert image description here
Then the following 7 situations are most likely to cause life cycle pitfalls:

getDerivedStateFromProps makes it easy to write anti-pattern code that blurs the distinction between controlled components and uncontrolled components.
componentWillMount has been marked as deprecated in React and is not recommended. The main reason is that the new asynchronous architecture will cause it to be called multiple times, so Network requests and event bindings should be placed in componentDidMount.
componentWillReceiveProps has also been marked as deprecated and replaced by getDerivedStateFromProps, mainly due to performance issues.
shouldComponentUpdate determines whether a new rendering needs to be triggered by returning true or false. Mainly used for performance optimization.
componentWillUpdate is also marked as obsolete due to the new asynchronous rendering mechanism and is not recommended. The original logic can be modified and used in combination with getSnapshotBeforeUpdate and componentDidUpdate.
If you forget to unbind events, cancel timers and other cleanup operations in the componentWillUnmount function, it is easy to cause bugs.
If error boundary handling is not added, the user will see an inoperable white screen when a rendering exception occurs, so it must be added.

Where should React requests be placed? Why?
For asynchronous requests, they should be placed in componentDidMount. From the perspective of the life cycle function execution sequence, there are two options besides componentDidMount: You can
put it in the constructor, but it is not recommended because the constructor is mainly used to initialize state and functions. Binding does not carry business logic, and with the popularity of class attributes, constructor is rarely used
. componentWillMount has been marked as obsolete, because under the new asynchronous rendering, this method will trigger multiple renderings, which is easy to cause bugs and is not conducive to React. Later maintenance and updates
, so placing React requests in componentDidMount is the best choice.

2. Tell me how the Real diff algorithm works?

The role of the diff algorithm
When the DOM needs to be updated, the diff algorithm can be used to calculate the truly changed parts of the virtual DOM, so that only the changed parts can be updated and rendered to avoid "impacting the whole body" and causing a waste of performance.

Although the ordinary diff algorithm
perfectly implements the function of finding differences, its fool-like loop recursion compares nodes sequentially, making the time complexity of the algorithm O(n^3), where n is the number of nodes in the DOM tree. . If the number of DOM is large enough, this algorithm will kill the CPU.

The diff algorithm in React
In order to optimize the diff algorithm, React implements three major strategies for the ordinary diff algorithm, successfully reducing the time complexity to O(n)

Strategy 1: tree diff - hierarchical comparison

Since cross-level movement of DOM rarely occurs during the development process, tree diff ignores cross-level movement of DOM nodes. (React does not recommend developers to move the DOM across levels)

component diff - component comparison

Two components of the same type are directly compared to the Virtual DOM tree. Components of different types will be judged as dirty components and be directly deleted or created.

Strategy three: element diff - node comparison

For a group of child nodes at the same level, they are distinguished by assigning a unique key value.

3. What does setState do in the reconciliation phase?

When calling setState, the first thing react does is integrate all the objects passed to setState into the state of the current component. This will start a "reconciliation" process. The purpose of the reconciliation process is to update the UI according to the new state in a more efficient way. To figure out how the new UI changes in response to the new state, React compares a new tree to the previous tree.

4. Talk about the implementation principle of redux and write the core code?

Why should we use redux for the secondary directory?

With the rapid development of the Internet, our applications have become more and more complex, and the relationship between our components has also become increasingly complex. It is often necessary to change the state parent component -> child component -> child child component -> again Or simply passing props between parent components and child components will also make our data flow difficult to maintain, because secondary developers cannot determine who initiated the data source without being familiar with the project. After using redux, all states come from the state in the store, and the store can be passed to all components under the Provider component through the Provider component in react-redux. That is to say, the state in the store is for the components under the Provider. Global.

What is the core principle of redux?

1. Unify the application status into state, and let the store manage the state.
2. The function of the reducer is to return a new state to update the corresponding state in the store.
3. According to the principle of redux, every state change in the UI layer should be triggered by an action. The action is passed into the corresponding reducer, and the reducer returns a new state to update the state stored in the store, thus completing a state update.
4. Subscribe is to subscribe to the listening function for the store. These subscribed listening functions are executed sequentially after each dispatch is initiated.
5. Middleware can be added to rewrite the submitted dispatch.

5.How does React synthesize events?

The react synthetic event mechanism adopts the idea of ​​event proxy and binds the native events that each react event depends on to the root element. The event processing function is not bound to the element of the component, but to the root. This is related to the structural characteristics of the fiber tree, that is, the event processing function can only be used as a prop of the fiber.
The event listener bound to the root is not the event handler function we wrote in the component, but a listener that holds the event priority and can pass the event execution stage flag.

6.How do React components communicate with each other?

Passing from parent component to child component
Since React's data flow is one-way, passing parent component to child component is the most common way.
When the parent component calls the child component, it only needs to pass parameters in the child component tag, and the child component passes props Properties can receive the parameters passed by the parent component. The basic idea of
​​​​passing a child component to a parent component
is that the parent component passes a function to the child component, and then through the callback of this function, it gets the parameters passed by the child component. Value
Communication between sibling components
If it is a transfer between sibling components, the parent component serves as an intermediate layer to realize data interoperability by using the parent component to transfer
Non-relational component transfer
If the relationship type between components is relatively complex, it is recommended to The data performs a global resource management to achieve communication, such as redux. The use of redux will be introduced in detail later.

7. Why does the react element have a $$type attribute?

The purpose is to prevent XSS attacks. Because Synbol cannot be serialized, React can
determine whether the current element object comes from the database or is generated by itself through the presence or absence of the typeof attribute. If there is no typeof attribute to determine whether the current element object comes from the database or is generated by itself. If there is no
typeof attribute to determine whether the current element object comes from the database or is generated by itself. Without
the typeof attribute, react will refuse to process the element.

8. What is the principle of Connect component?

The principle of Connect is to use Provider in the entry file to wrap the entire component and make it its sub-component. It accepts the store in redux as props, and then passes it to the connect on the descendant component through the context.

作用:连接React组件与Redux Store
mapStateToProps允许我们将 store 中的数据作为 props 绑定到组件上
mapDispatchToProps将action作为props绑定到MyComp上。
mergeProps不管是stateProps还是dispatchProps,都需要和ownProps merge 之后才会被赋给MyComp。connect的第三个参数就是用来做这件事。通常情况下,你可以不传这个参数,connect就会使用Object.assign替代该方法。
 
首先connect之所以会成功,是因为Provider组件:
 
在原应用组件上包裹一层,使原来整个应用成为Provider的子组件
接收Redux的store作为props,通过context对象传递给子孙组件上的connect
那connect做了些什么呢?
 
它真正连接 Redux 和 React,它包在我们的容器组件的外一层,它接收上面 Provider 提供的 store 里面的 state 和 dispatch,传给一个构造函数,返回一个对象,以属性形式传给我们的容器组件。
 
关于它的源码
 
connect是一个高阶函数,首先传入mapStateToProps、mapDispatchToProps,然后返回一个生产Component的函数(wrapWithConnect),然后再将真正的Component作为参数传入wrapWithConnect,这样就生产出一个经过包裹的Connect组件,该组件具有如下特点:
 
通过props.store获取祖先Component的store
props包括stateProps、dispatchProps、parentProps,合并在一起得到nextState,作为props传给真正的Component
componentDidMount时,添加事件this.store.subscribe(this.handleChange),实现页面交互
shouldComponentUpdate时判断是否有避免进行渲染,提升页面性能,并得到nextState
componentWillUnmount时移除注册的事件this.handleChange
 
 
 
export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {
     
     }) {
    
    
  return function wrapWithConnect(WrappedComponent) {
    
    
    class Connect extends Component {
    
    
      constructor(props, context) {
    
    
        // 从祖先Component处获得store
        this.store = props.store || context.store
        this.stateProps = computeStateProps(this.store, props)
        this.dispatchProps = computeDispatchProps(this.store, props)
        this.state = {
    
     storeState: null }
        // 对stateProps、dispatchProps、parentProps进行合并
        this.updateState()
      }
      shouldComponentUpdate(nextProps, nextState) {
    
    
        // 进行判断,当数据发生改变时,Component重新渲染
        if (propsChanged || mapStateProducedChange || dispatchPropsChanged) {
    
    
          this.updateState(nextProps)
            return true
          }
        }
        componentDidMount() {
    
    
          // 改变Component的state
          this.store.subscribe(() = {
    
    
            this.setState({
    
    
              storeState: this.store.getState()
            })
          })
        }
        render() {
    
    
          // 生成包裹组件Connect
          return (
            <WrappedComponent {
    
    ...this.nextState} />
          )
        }
      }
      Connect.contextTypes = {
    
    
        store: storeShape
      }
      return Connect;
    }

9. Tell me about your understanding of fiber architecture? What problem was solved?

what is

React Fiber is a major change and optimization that Facebook spent more than two years making to React. It is a re-implementation of React's core algorithm. Confirmed by Facebook at the React Conf 2017 conference, React Fiber was released in React 16.
In react, it mainly does the following operations:
adding a priority to each, and high-priority tasks can interrupt low-priority tasks. Then try again, pay attention to re-executing low-priority tasks.
Add an asynchronous task, call the requestIdleCallback api, and execute the dom when the browser is idle. The
diff tree becomes a linked list. One dom corresponds to two fibers (one linked list), corresponding to two Queue, which is all about finding interrupted tasks and re-executing them.

From an architectural perspective, Fiber is a rewrite of React’s core algorithm (i.e., the reconciliation process).
From a coding perspective, Fiber is a type of data defined internally in React. Structure, which is the node unit of the Fiber tree structure, which is the virtual DOM under the new architecture of React 16

How to solve

Fiber splits the rendering update process into multiple subtasks, and only does a small part of it each time. After completing it, see if there is still time left, and if so, continue with the next task; if not, suspend the current task and hand over time control. The main thread will continue execution when the main thread is not busy.

That is, it can be interrupted and restored, and the previous intermediate state can be reused after restoration, and different priorities are given to different tasks. Each task update unit is the Fiber node corresponding to the React Element.

The above method is implemented by the requestIdleCallback method

The window.requestIdleCallback() method queues functions to be called during the browser's idle periods. This enables developers to perform background and low-priority work on the main event loop without affecting delayed critical events such as animations and input responses

First, tasks in React are divided into multiple steps and completed in batches. After completing part of the task, control is returned to the browser, allowing the browser time to render the page. It is a kind of cooperative scheduling to wait for the remaining time after the browser is finished, and then continue the unfinished tasks of React.

The implementation process is based on Fiber nodes. As a static data structure, each Fiber node corresponds to a React element, which stores the type of the component (function component/class component/native component, etc.), the corresponding DOM node, etc. information.

10. Tell me about your understanding of redux middleware? What are the commonly used middleware? Implementation principle?

what is

In computers, middleware is a type of software between application systems and system software. It uses the basic services (functions) provided by system software to connect various parts of the application system or different applications on the network. It can achieve the purpose of resource sharing and function sharing.
In this article, I learned about the entire workflow of Redux. When the action is issued, the reducer immediately calculates the state. The whole process is a synchronous operation.
If you need to support asynchronous operations or support error handling , log monitoring, this process can use middleware

Commonly used middleware

redux-thunk: for asynchronous operations
redux-logger: for logging

11.What are the methods to optimize React performance?

React is very stable through methods such as virtual dom, but in some specific cases, we still need to perform performance optimization. What are the methods of performance optimization? The first one is server-side rendering, the second one is Lazy loading of components, the third react uses component libraries to avoid arbitrary marking, and the fourth is event binding.

12. Tell me about your understanding of event loop?

First of all, JavaScript is a single-threaded language, which means that only one thing can be done at the same time. However, this does not mean that single-threading is blocking. The way to achieve single-threaded non-blocking is the event loop.

In JavaScript, all tasks can be divided into

Synchronous tasks: tasks that are executed immediately. Synchronous tasks generally enter the main thread for execution directly.

Asynchronous tasks: tasks executed asynchronously, such as ajax network requests, setTimeout timing functions, etc.

13. Front-end cross-domain solution?

JSONP cross domain

The principle of jsonp is to use

Cross-Origin Resource Sharing (CORS)

CORS is a W3C standard, whose full name is "Cross-origin resource sharing".
It allows the browser to issue XMLHttpRequest requests to cross-origin servers, thus overcoming the limitation that AJAX can only be used from the same origin.
CORS requires both browser and server support. Currently, all browsers support this function, and IE browser cannot be lower than IE10.
Browsers divide CORS cross-domain requests into simple requests and non-simple requests

14. Commonly used methods and functions of arrays, at least 15?

join() (array to string)
push(): method adds one or more elements to the end of the array and returns the new length.
pop(): method is used to remove and return the last element of the array.
shift(): method is used to remove the first element of the array and return the value of the first element.
unshift(): Method adds one or more elements to the beginning of the array and returns the new length.
sort() (sort)
reverse() (reverse array)
concat() (connect two or more arrays)
slice() (array interception)
splice()
indexOf()--------array.indexOf (item,start) (search backwards from the beginning of the array (position 0))
item: required. The element to find.
start: optional integer parameter. Specifies the position in the array to start searching. If this parameter is omitted, the search will start from array[0].
lastIndexOf()--------array.lastIndexOf(item,start) (search forward from the end of the array)
item: required. The element to find.
optional integer argument to start. Specifies the position in the array to start searching. If this parameter is omitted, the search will start from array[array.length-1].
forEach(): loops through the array. This method has no return value. jquery() also provides the corresponding method each() method.
map(): refers to "mapping". The method returns a new array. The elements in the array are the values ​​of the original array elements after calling the function.

15. How does the React render method work? When is it triggered?

The React render method is expressed differently in class components and function components.
In class components: the render method refers to the render method;
in function components: the render method refers to the function component itself;
in the render method, react compares the new dom returned by the newly called render with the old dom , this is a necessary step to update the dom, and then perform diff calculation to update the dom tree.
In class components, when the setState method is called to refresh data, the render function will be triggered.
In function components, when useState hook is used, the data will be updated.

16. Tell me about your understanding of mixin in Vue?

Mixins provide a very flexible way to distribute reusable functionality in Vue components.
The essence is actually a js object, which can contain any functional options in our components, such as data, components, methods, created, computed, etc. We only need to pass the
shared functions into the mixins option in the form of objects. When the component uses the mixins object At this time, the options of all mixins objects will be mixed into the options of the component itself.
In Vue, we can mix locally and globally.
Prioritize recursive processing of mixins.
First traverse and merge the keys in the parent, call the mergeField method to merge, and then save it in the variable options.
Then traverse the child, merge and fill in the keys that are not in the parent, call the mergeField method to merge, save it in the variable options, and
merge it through the mergeField function.

17. What is the difference between for...in loop and for...of loop?

for of Characteristics The for of loop is used to obtain the value in a pair of key-value pairs, while for in obtains the key name. As long as a data structure is deployed with the Symbol.iterator attribute, it is regarded as having the iterator interface, and you can use for of cycle.

18.What are the ways to judge data types in JS? Name at least 5? What's the difference?

The first is: typeof method, which returns a string type.
The second instanceof method expresses A instanceof B.
The third contextof is an attribute on the js prototype object.
The fourth, object, prototype, and toString can be used. Check the object type
Fifth, Array, isArray() to determine whether the data group type

19. Tell me about your understanding of Object.defineProperty()?

Object.defineProperty () allows precise addition or modification of a property on an object. Properties added through const obj = {};obj.foo = 1 can be enumerated through for...in or Object.keys, and their values ​​may change or be deleted.

20. Tell me about your understanding of webSocket?

Understanding of WebSocket: webSocket is a network communication technology for full-duplex communication between the server and the browser provided by HTML5. It belongs to the application layer protocol. It is based on the TCP protocol and reuses the http handshake channel. The browser and server only need to complete a handshake to complete a permanent connection and enable two-way communication.
The principle of WebSocket: The server notifies webSocket of an event with all receiver IDs. After the server receives it, it notifies all active clients. Only those with IDs in the receiver sequence can handle this event.

Guess you like

Origin blog.csdn.net/qq_53509791/article/details/129124791