Front-end interview questions react technology stack

In the process of contacting the front-end, we know that there are two commonly used technology stacks. The first is vue2/vue3, and the other is react. Personally speaking, I think vue is relatively simple. After all, it has been written We can just take some of the dead APIs and use them directly. Basically, they will achieve the functions we want. Vue also has a lot of UI frameworks, which is a relatively convenient technology stack. As for react, I personally think it is quite good. , I prefer the react technology stack.

The difference between vue and react.

Common points:

  1. Data driven view.

  1. Componentization.

  1. virtua DOM

difference:

  1. The core ideas are different.

  1. There are differences in writing styles.

  1. The diff algorithm is different.

  1. The principle of responsiveness is different.

  1. Source code differences

  1. ........etc.

Understanding of react.

React, a JavaScript library for building user interfaces, provides UI-level solutions that follow component design patterns, declarative programming paradigms, and functional programming concepts to make front-end applications more efficient, using virtual DOM to effectively manipulate DOM , following the one-way data flow from high-order components to low-order components, helps us divide the interface into independent small blocks. Each block is a component. These components can be combined and nested to form an overall page.

Its advantages:

- Efficient and flexible

- Declarative design, easy to use

- Component-based development to improve code reuse rate

- One-way response data flow will be safer and faster than two-way binding

Understanding of React event mechanism.

React itself implements a set of event mechanisms based on the browser's event mechanism, including event registration, event synthesis, event bubbling, event dispatch, etc. In React, this set of event mechanisms is called synthetic events;

Synthetic events are an event object that React simulates all the capabilities of native DOM events, that is, a cross-browser wrapper for browser native events.

Execution order

All events in React are mounted on the document object

When the real DOM element triggers the event, it will bubble up to the document object and then handle the React event.

So the native event will be executed first, and then the React event will be processed

Finally, the event mounted on the document is actually executed.

Summarize

Events registered on React will eventually be bound to the DOM of the document, rather than the DOM corresponding to the React component (memory overhead is reduced because all events are bound to the document, and other nodes have no bound events)

React itself implements an event bubbling mechanism, so this is why our event.stopPropagation() is invalid.

React traces back from the triggered component to the parent component through a queue, and then calls the callback defined in their JSX

React has its own set of synthetic events, SyntheticEvent

React is trying to update.

Because React is a one-way data flow and the data drives the UI, there are several ways to try to update in React.

Method 1: setState

setState is the most common way to update a view as we all know. You only need to give an initial state and call this.setState when it needs to be updated. The component will go through the four processes of shoudlComponentUpdate => componentWillUpdate => render => componentDidUpdate. If it is not in shouldComponentUpdate If you manually return false, the ui will be updated at this time.

It should be noted that although the parameter this.setState({}) is an empty object, react will still update and call the above four life cycles, but the ui view will not change.

Of course, these are all based on class components, because setState is a method on the Component prototype, and a component must inherit Component to call this.setState.

Method 2: useState();

The operation of state value through useState can only be called in the React function by passing in the useState parameter and returning an array with the default state and the change state function. Changing the original state value by passing the new state to the function is often used with useEffect.

Method three: forceUpdate

After calling forceUpdate, the current component will skip the shouldComponentUpdate hook. Even if you return false manually, it will still be updated. The literal meaning of the word is also a forced update . However, it should be noted that the update of sub-components will still be controlled by shouldComponentUpdate.

The usage scenario of forceUpdate is generally that the view update comes from other non-state and props data, such as properties bound to component instances, or directly modifying this.state.xxx = xxx and then calling this.forceUpdate(), but the official This is not recommended. Under normal circumstances, you should avoid using forceUpdate and update the view through state or props.

Method 4: Manipulate DOM natively

In React, there will inevitably be times when you need to operate the native DOM. For example, if you use a third-party library such as jquery that needs to obtain the DOM, or you need to implement a drag-and-drop, two-finger zoom component, for these, you may be able to use operations The dom method bypasses react's setState and then dom diff a series of calculations, directly updates the dom, and improves some performance.

For the above three methods of updating ui, it should be noted that when the color is changed to red through setState update, and the color is changed to green when clicking the native dom button, when the setState button is clicked, the view is not updated, but the render is still gone. function, this is because before clicking the native dom button, the value of this.state.backgroundColor is red, and the native operation is to directly change the dom style. After clicking the setState button, in fact, the value of this.state.backgroundColor is still red, even though it has been updated. Logic, but when comparing the old and new virtual DOM of React, it was found that the color has not changed, resulting in no patch to the UI.

Method five: dispatch action

The above methods all use the state that comes with react to update the UI. When using redux in a project, we usually dispatch an action, change the store, and then update the UI. The dispatch action drives the view by changing props. , when you are using it, have you ever thought about why this.props.dispatch({ type: 'xxx' }), can drive the ui view update?

Let me briefly explain here, when we dispatch an action, what is actually called is store.dispatch. This is no problem. store.dispatch will run through all the reducers registered in createStore to find the corresponding type update data. Return a new state.

If our component wants to get the store data, it must go through connect(mapStateToProps, mapDispatchToProps)(App). Like this, the Connect component in react-redux will call a trySubscribe method when componengDidMount, and internally call store.subscribe. Subscribe to a handleChange method.

So when you dispatch an action, the method in the Connect component will be triggered. The Connect component also maintains a state called storeState. Every time you get a new store, you will call setState to trigger the render function. The render function will be based on your The mapStateToProps and mapDispatchToProps passed in connect, including the optional parameter mergeProps, perform a merging action of props, and finally return something like createElement(WrappedComponent, this.mergedProps) inside the Connect component, and the second parameter of createElement is The props of your component, then every time the props change, it will drive the update of the view.

Summarize
  1. Change the state of the driven view by calling this.setState.

  1. Update views by using hooks.

  1. Force a view to be updated by calling this.forceUpdate.

  1. Update the view by manipulating the native DOM.

  1. Drive the view by changing props (redux or modify parent-child components to pass props).

Function component hooks

1. With Hooks, function components can no longer be called stateless components, because Hooks can provide state for function organizations

2. Hooks are features that allow you to "hook into state and life cycle" in function components.

3. Function components can only be used for display, because they have no state, no life, etc., so the things they can do can only be displayed.

4. Hooks can only be used for function components, which makes up for its shortcomings. It can be understood as having heard that Hooks hook into classes for function components, and useEffect is the representative feature of the component.

5. Hook appeared in react 16.8

6. Pure function render Function components are all pure functions, and the same parameters with high performance must return the same value.

Commonly used hooks

1 useState() changes state

2 useEffect() must be asked in interviews. return ()=>{} is used as a life cycle

3 useCallback(()=>{},[]) cache function

4 useMemo(()=> must have renturn,[]) to cache data

5 useRef. High chance of interview

6 useContext() is used together with context to communicate between sending and receiving components.

7 useReducer() understand react

8 useParams dynamic routing parameters

9 useLoaction routing information

10 useNavigate react-router-dom v6 programmatic routing

11 useSelector

12 useDispatch redux

antd just

message.useMessage()

Form.useForm

useState function component state

The operation of state value through useState can only be called in the React function by passing in the useState parameter and returning an array with the default state and the change state function. Changing the original state value by passing the new state to the function is often used with useEffect.

useEffect

Let functional components simulate life cycles

1. The default function component has no life cycle

2. The function component is a pure function, which is destroyed after execution and cannot implement its own life cycle.

3. "Hook" the life cycle into pure functions through Effect hook

4. The logic executed by the first parameter callback

()=>{

//Business logic

return ()=>{ dependency changes, component destruction execution}

}

// second parameter

1 does not write, which is equivalent to the update phase + the mount phase. It is executed once by default and is also executed during the update.

2 [] is only created and executed once, which is equivalent to the mount phase life cycle.

3 [Dependency 1, Dependency 2] As long as the dependency changes, the callback is executed. The callback is similar to vue monitoring.

use Memo

The returned value obtained by calculating the attribute useMemo is the returned result.

useMemo is for a function. Whether it is executed multiple times is mainly used to solve the performance problem of useless rendering caused by using React hooks.

In the method function, since shouldComponentUpdate cannot be used to handle performance issues, react hooks added useMemo.

useMemo use

If the second parameter of useMemo(fn, arr) matches and its value changes, it will be executed multiple times, otherwise it will only be executed once. If it is an empty array [], fn will only be executed once.

useCallback

First of all, it is a high-performance function and a closure

In functional components, useCallback is used to cache the function (wrapped by an outer function, equivalent to a closure). When the component is updated again (the function is re-executed), the cache function [previously generated function] or the new one will be decided based on whether the dependencies have changed. Function [newly generated context].

Generally, it is used in nested components with memo of functional components and PureComponent of class components [a shallow comparison of the incoming props parameters will be performed one by one to determine whether they need to be updated] to improve page performance.

UseRef

Usually we render components in divs, but this time we have a point to pay attention to, that is, when we update the state, it will cause the component to be re-rendered, so my component was rendered for the first time, declared and changed. state, then trigger rendering, and re-declare the changed state, which will cause my component state to enter an infinite loop, establishing itself in the infinite loop... This will greatly reduce performance and increase memory usage, so at this time we Useref will be used because the value change of useRef is not affected by rendering and will not be updated again.

useParams dynamic routing parameters

const params = useParams()

navLink to="/topic/123"

path:"/topic/:id"

console.log(params,'params')

Programmatic routing useNavigate

import {useNavigatet} from 'react-router-dom'

function App(){

const native = useNavigate()

}

navigate('address') push, mode

navigate("/address",{replace:true}) has no back record and replace mode

navigate(1,-1,0) forward, backward and refresh

Routing information useLocation

1 Reasons to use routing information as navigation guard

2 location.pathname to log in to access

//Navigation guard

function App(){

const location = useLocation();

const navigate = useNavigate();

// Must be logged in to access

useEffect(() => {

// console.log("Entered:" + location.pathname);

if (isLogin) {

console.log("Already logged in");

} else {

navigate("/login");

}

// Navigation guard

}, [location.pathname]);

}

// Home page about details page

/**

Home page free access

The other three pages must be logged in to access.

Local storage storage status to determine whether to log in

React Diff algorithm

The diff algorithm** is a concept derived from virtual DOM. It is used to calculate the truly changed part of the virtual DOM and perform native DOM operations only on this part instead of re-rendering the entire page, thereby** improving page rendering efficiency. **.

Calling React's render() method creates a tree consisting of React elements. The same render() method will return a different tree the next time state or props are updated. React needs to update the UI based on the difference between these two trees.

There are some general solutions to this algorithmic problem, which is to generate the minimum number of operations that transform one tree into another. However, even among state-of-the-art algorithms, the algorithm has a complexity of O(n 3 ), where n is the number of elements in the tree.

If this algorithm were used in React, the amount of calculations required to display 1000 elements would be in the range of a billion. This cost is simply too high.

In order to reduce the complexity of the algorithm, React proposes a set of O(n) heuristic algorithms through some restriction strategies.

Talk about the compilation principle of JSX

It plays an important role in describing the UI interface and associated rendering logic in [React]( https://so.csdn.net/so/search?q=React&spm=1001.2101.3001.7020)

JSX=javascript xml is a format that combines Javascript and XML. Is a syntax extension for JavaScript

jsx is very similar to HTML in structure, but its essence is still js language.

Babel tool compiles jsx syntax

JSX performs faster because it is optimized after being compiled into JavaScript code.

It is type-safe and errors can be caught during compilation.

Writing templates using JSX is easier and faster.

setSate

setSate accepts two parameters, one is state (value), the other is [callback function]( https://so.csdn.net/so/search?q=callback function&spm=1001.2101.3001.7020) It is asynchronous

The callback function is called when this value is completed.

redux

Redux centrally manages all states. When the state needs to be updated, you only need to centrally handle this management without caring about how the state is distributed to each component. Redux is a container that implements centralized management.

Follow three basic principles: single data source, state is read-only, and pure functions are used to perform modifications.

It is a shared data state three-part action store reducer. Generally speaking, redux is related to component communication.

If you don't use redux, you can only use React's own mechanisms such as improving the communication status of parent-child components. It will be very inefficient to handle non-parent-child communication. The data flow between components is confusing and prone to bugs.

Use redux to centrally store and manage application status to handle component communication issues. It can ignore hierarchical relationships between components and simplify communication issues between components in large and complex applications. The data flow is clear and easy to locate bugs.

redux is usually used together with react-redux and context

Redux workflow:

Dispatch the action method to the store through dispatch. After the store receives the action method, it passes the state and action methods to the reducers. After the reducers receive the state and action methods, they will modify their state and return a new state value to the store.

redux-middleware

Application dispatch task (during the dispatch process, I want to do some contextual operations and provide me with a contextual environment

The middleware operates the dispatch step and executes asynchronous vuex actions.

1 redux-logger print log()

2 redux-thunk \

//First, the store page introduces thunk for use

3 reudx-promise

dispatch(new Promise((resolve,reject)=>{}))

4 redux-saga

react-redux

react+redux and redux are used together in react projects

1 redux update problem (not synchronized with react)

2. Introduction to the problem is a bit troublesome to use. It needs to be introduced every time.

npm i react-redux --save

ProducerProvider

Need to be introduced in main.tsx

import {Provider} from "react-redux"

Provider store={store}

App

consumerconnect()

redux persistent storage

Generally means that after the page is refreshed, the data can still maintain its original state.

Generally in the front-end, data persistence can be done by storing the data in localstorage or cookies.

Get data directly from local storage. And redux-persist stores the data in redux in localstorage, which plays the role of

Long-lasting effects.

Component communication

1: Passed from parent to child, the child component receives it through props.

Two: Customize components to serve as bridges between components for parameter communication.

Three: redux persistent storage.

Four: context. Context provides data on the parent component, and then all descendant components of the secondary component can share state and methods.

react-router与react-router-dom

React-router: implements the core functionality of routing

**React-router-dom: Based on React-router, it adds some functions that run in the browser. In most cases when using React, we will want to control routing by operating dom, such as clicking a - button The jump is completed. It is more convenient to use React-router-dom at this time. And installation is also simple

Determine the type of array

1. Judge by Array.isArray()

2. Judge by Object.prototype.toString.call()

3.instant of

promise

Promise is used to make code execute in order. It was first used to solve the problems of callback hell and asynchronous requests. It has two parameters and four methods, resolve and reject. One of them is called successfully and the other is failed. When called, .then will be executed when it succeeds. .catch will be executed when it fails. Return in .then can continue.then. The parameter of next .then is the value of the previous .then return. This feature is used to ensure that the code can Execute in the order we want. Let’s talk about the states of Promise. There are three types of Promise: waiting-success-failure. The same Promise has only one state in the same timestamp and this state is irreversible. When Promise.then is executed, it essentially creates a new Promise object (Promise.prototype.then) and has a new state. Promise has four common methods. then .catch .all .race

I won’t talk about .then and .catch just now ----- Promise.race passes an array. If one of the functions in the array succeeds, its status is successful (it may be used to grab tickets, specifically I haven't studied it yet)------Promise.all passes in an array, and a bunch of functions in the array must all be executed to succeed.

Many times Promise is used in conjunction with async--await, for example, requesting data from two interfaces A and B, using the data requested by A interface to be passed as a parameter to B interface, and at the same time requiring the return of the spliced ​​data jointly requested by A and B. As a result (the application scenario can be said not to mention scanning the QR code to log in), await cannot be used alone, async can be used. Declaring an async function can always await in the function body and wait for the code to be executed before executing the next line of code, which can ensure that the code is executed in order. One thing to note is that await only waits for synchronization and microtasks. Macrotasks will still be added to the macrotask queue to wait, and will not wait for execution in the main thread. There is a disadvantage that needs to be noted because js is single-threaded. await Waiting for code execution means that it will block the running of the program and affect performance. If you need to render data or do calculations at this time, you can consider using Web Worker to create a new js sub-thread to perform data and calculation operations, or in a js sub-thread. Request data because the js sub-thread cannot operate the DOM element of the page. The async function has no return value. The return value of the await function is a Promise object. The .then call is OK.

The difference between js and ts

First, they are both scripting languages. JavaScript is a lightweight interpreted scripting language that can be embedded into HTML pages and executed on the browser side. TypeScript is a superset of JavaScript (ts is an open source programming language developed by Microsoft), which includes all elements of JavaScript, can run JavaScript code, and extends JavaScript syntax. (ts contains js libraries and functions. You can write any js on ts, call any js library, and use native js syntax in ts). Compared with JavaScript, it also adds functions in static types, classes, modules, interfaces and type annotations, making it easier to develop large projects.

1. TypeScript introduces the concept of "class" that is not found in JavaScript

2. TypeScript introduces the concept of modules, which can encapsulate declarations, data, functions and classes in modules.

3. JS does not have the concept of overloading, but ts can be overloaded.

4. ts adds interfaces, generics, classes, class polymorphism, inheritance, etc.

Some types of js: boolean type, number type, string type, array type, undefined, null

New types added to ts: tuple type (tuple type), enum type (enumeration type), any type (any type)

The void type (without any type) means that the defined method has no return value

Never type: is a subtype of other types (including null and undefined), representing values ​​that never appear. This means that declaring a never variable can only be assigned a value of the never type.

JS variables have no type, that is, age=18, age can be of any type, and you can continue to assign age as age="aaa"

Ts has a clear type (ie: variable name: number (numeric type)) eg: let age: number = 18

.The difference between class components and function components

The main differences are:

Class components have a life cycle, but function components do not;

Class components are created by relying on class, and function components are created by return;

Class components have state storage, and function components need to rely on Hooks to complete state storage;

Special attention needs to be paid to the issue of this pointing in class components, while function components do not have this;

Class components consume a lot of money and need to create instances and cannot be destroyed; function components consume little and are destroyed when the results are obtained.

1. Function component syntax is shorter and simpler, which makes it easier to develop, understand and test.

2. Class components can also be confusing due to extensive use of this. Using functional components you can easily avoid this shortcoming and keep your code clean.

3. When the business logic is complex, using class components is easier for us to maintain, which also reduces development costs accordingly.

4. Function components are mostly used to encapsulate simple functional modules for easy reuse.

Cross-domain issues and solutions

Cross-domain does not necessarily have cross-domain problems.

Because the cross-domain problem is a security restriction of the browser for ajax requests: an ajax request initiated by a page can only be a path with the same domain name as the current page, which can effectively prevent cross-site attacks. Cross-domain issues are a limitation of ajax. But this brings inconvenience to our development, and in the actual production environment, there will definitely be many servers interacting with each other, and the addresses and ports may be different.

Solution:

CORS standardized cross-domain request solution, safe and reliable. CORS is a W3C standard, the full name is "Cross-origin Resource Sharing". It allows browsers to issue [`XMLHttpRequest`] ( http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html) to cross-origin servers. request, thereby overcoming the limitation that AJAX can only be used with [same origin]( http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html)

Access-Control-Allow-Origin: http://manage.leyou.com

Access-Control-Allow-Origin: The acceptable domain is a specific domain name or *, which represents any Access-Control-Allow-Credentials: true

Access-Control-Allow-Credentials: Whether to allow cookies to be carried. By default, cors will not carry cookies unless this value is true.

Front-end performance optimization

1. Shallow rendering: The overhead of comparing primitives and object references is lower than updating component views, so finding changes in state and props values ​​will be faster than unnecessary updates

2. Use React.memo for component memory: If the input props are the same, component rendering will be skipped, thereby improving component performance. It will remember the execution output of a certain input prop last time and improve application performance.

3. Use the shouldComponentUpdate life cycle event: This is one of the life cycle events that is triggered before the component is re-rendered. This event can be used to determine when the component needs to be re-rendered

4. Lazy loading: Suspense and lazy

5. Use React Fragments to avoid extra tags

6. Use pure functions

7.Css style uses external links

8. Reduce conditional rendering in React

1. Reduce the number of requests (1. Pictures: Sprite pictures, Base64, use font icons instead of pictures. 2. Reduce redirections (when the page is redirected, it will delay the transmission of the entire HTML document. Before the HTML document arrives, Nothing will be rendered on the page, and no components will be downloaded, which reduces the user experience. If you use 301 permanent redirect) 3. Not using css@import will cause additional requests. 4. Avoid using empty src and href)

2. Reduce redraw reflow

  1. Use APIs with good performance (1. Use the corresponding selector. 2. Use requestAnimationFrame instead of setTimeout and setInterva. You hope to change the page at the beginning of each frame. requestAnimationFrame tells the browser that you want to execute a animation, and requires the browser to call the specified callback function to update the animation before the next redraw. This method needs to pass in a callback function as a parameter. The callback function will be executed before the browser redraws next time. Use setTimeout or setInterval to trigger A function that updates the page. This function may be called in the middle or at the end of a frame, which may cause the things that need to be done later in the frame not to be completed, resulting in frame loss)

Macro tasks and micro tasks

Macro tasks are executed after being initiated by the host browser\1. script (can be understood as outer synchronization code) 2. setTimeout/setInterval 3. run after promise().then

Microtask is js engine\1. Promise2. MutaionObserver3. Object.observe (obsolete; replaced by Proxy object) 4. process.nextTick runs first

Execution order: Execute the synchronous code first. If an asynchronous macro task is encountered, the asynchronous macro task will be placed in the macro task queue. If an asynchronous micro task is encountered, the asynchronous micro task will be placed in the micro task queue. When all synchronous codes are executed, Then the asynchronous microtasks are transferred from the queue to the main thread for execution. After the microtasks are executed, the asynchronous macrotasks are transferred from the queue to the main thread for execution, and the cycle continues until all tasks are executed.

The page requesting a large amount of data is stuck.

From the front-end perspective, load in batches and lazy load. Using workers,

Because the worker js runs in a single thread, when it encounters some js that need to process a large amount of data, it may block the loading of the page, causing the page to freeze. At this time, we can use the worker to open up a sub-thread independent of the main thread to perform a large number of operations. This will prevent the page from getting stuck.

It has two parameters:

aURL (required) is a DOMString representing the URL of the script that the worker will execute. It must comply with the same-origin policy.

options (optional) One of its functions is to specify the name of the Worker to distinguish multiple Worker threads

Guess you like

Origin blog.csdn.net/weixin_42602736/article/details/128885624