Front-end interview stereotyped essay (detailed version) - medium

The previous article explained HTML, CSS, JavaScript, computer network knowledge, etc. in detail. This article will explain React, git, webpack, etc. in detail . I wish you a successful landing!

 React framework


Use react scaffolding to build projects

npx create-react-app app-name

The difference between class and function

Components defined by function can use hooks to set state and simulate life cycle, there is no this to point to the problem. The code is simpler and easier to understand, full of functional components, very easy to understand.

The current version of react is version 17

What's the difference between 17 and 16?

What changes after equivalent to react16.8?

详细介绍:
https://segmentfault.com/a/1190000040453119?utm_source=sf-similar-article

Common UI library

Add rich text

dangerouslySetInnerHTML={
   
   { __html: this.state.newHtml }}

Which one executes first between component binding and js native binding event?

Execute the js native binding event first, and then execute the synthetic event, because the synthetic event occurs in the bubbling stage

What are synthetic events in React?

Synthetic events are objects that act as cross-browser wrappers around browser-native events. They combine the behavior of different browsers into one API. This is done to ensure that events display consistent properties across browsers;

What are the two types of components in react?

  • class component
  • function component

hooks

Advantages of hooks

The code is more readable. The original code logic of the same function is split into different life cycle functions, which makes it difficult for developers to maintain and iterate. Function codes can be aggregated through React Hooks, which is convenient for reading and maintenance

  useState,定义局部状态
  useEffect,模拟生命周期
  useContext,获取上下文
  useCallback,缓存一个function
  useMemo,缓存一个值
  useReducer,又一种存储数据的形式

 当组件的属性或者数据改变的时候组件会重新刷新(就是组件的 function 会重新被执行)

useState, define local state

Local state data can be defined in the component defined by function, and the component will re-render when the data changes

Returns an array, the first item of the array is a variable name, and the second item is the method to change the data. It should be noted that parameter two

There are two ways to use the method of changing data:

  • 1. is directly a value
  • 2. You can set a function, the last value of a state data is passed in the function by default, and the return value of the function will be used as the latest value of the state data. It is recommended to use this method to change state data

useEffect, simulate life cycle

The life cycle hook function of the component can be simulated in the component defined by function

Parameter 1 is a callback function Parameter 1 can return a function, and the returned method is executed when the component is destroyed

The second parameter is a dependency array. in three forms

  • 1. If parameter 2 does not exist, the callback function will be executed every time the component is updated;
  • 2. If parameter 2 is an empty array, it will only be executed once during initialization;
  • 3. If there is data in the array in parameter 2, the callback function will be executed when each item in the array is changed;

useMemo, cache a value

The function is to cache a value, which receives two parameters, the first parameter is a cached value, and the second parameter is a dependency;

useCallback

The function is to cache a function, which receives two parameters. The first parameter is a callback function, and the second parameter is a dependency. When the dependency array in the second parameter does not change, the function will not be redefined;

useReducer

The role of the role is to do a data management, which is based on a one-way data flow.

useReducer can be understood as a simplified version of redux

Receive two parameters: parameter one is a function, parameter two is an initial value

Return an array: the first item is the state data, and the second item is the dispatch method

If you want to change the data, you can only dispatch an action through dispatch

memo

memo is a function that receives a component as a parameter and returns a new component. The function is to cache the component, and the component will not re-render when the properties received by the component do not change

The memo API is recommended during development to facilitate component performance optimization

The role of memo is to cache components and make shallow comparisons of component properties. Components don't update when properties haven't changed. The function is to facilitate the performance optimization of components, which has the same effect as pureComponent

The difference between Component and PureComponent

Component does a deep comparison (each layer compares)

PureComponent does a shallow comparison (only the first comparison)

Relatively speaking, the performance of PureComponent components is better

If it is a normal component, when the component receives new props, render will re-render. If it is pureComponent, then when new props are passed in, it will perform a shallow comparison with the old props. If there is no change, then the render function will not Re-render.

useRef

The function is to get the dom element in the react component

The difference between useMemo and useCallback

useMemo caches a value

useCallback is to cache a function

Their second parameter is the dependent array. When the data in the dependent array changes, the cached value will be updated again.

useCallback will not execute the first parameter function, but return it to you, and useMemo will execute the first function and return the function execution result to you. So useCallback often remembers event functions, generates memorized event functions and passes them to subcomponents for use. And useMemo is more suitable for obtaining a certain value through function calculation, such as memory components.

Notes on hooks:

As mentioned in the official React documentation, hooks cannot be used in conditions/loops, but can only be written at the top of functional components/in custom hooks, which has order problems;

What are custom hooks

Define a useXxx method yourself. Custom hooks, which can strip and encapsulate business logic code

为了界面更加美观。获取浏览器窗口的尺寸是一个经常使用的功能,这样经常使用的功能,就可以封装成一个自定义Hooks函数。
新建一个文件Example9.js,然后编写一个 useWinSize,编写时我们会用到useState、useEffect和useCallback所以先用import进行引入
import React, { useState ,useEffect ,useCallback } from 'react';
然后编写函数,函数中先用 useState 设置size状态,然后编写一个每次修改状态的方法onResize,这个方法使用useCallback,目的是为了缓存方法(useMemo 是为了缓存变量)。
然后在第一次进入方法时用useEffect来注册resize监听时间。为了防止一直监听所以在方法移除时,使用 return 的方式移除监听。
最后返回 size 变量就可以了。
https://zhuanlan.zhihu.com/p/264304340

class

The life cycle of class components:

  1. initialization phase

    constructor (execute setting properties and state data during initialization)

  2. mount phase

    componentWillmount (executed before mounting)

    [Important] componentDidMount (executed after the mount is completed): execute the data acquisition operation in this lifecycle hook function, and call the interface to fetch data

  3. update phase

      componentWillReceiveProps (executed when new properties are received)

    [Important] shouldComponentUpdate (judging whether the component needs to be updated):

    This method is often used when optimizing component performance. This method receives two parameters (new property and new state) and returns a bool value. This method is often used in component performance optimization using componentWillUpdate (component will be updated) componentDIdUpdate (component update completed)                                                                                        

    	shouldComponentUpdate(np, ns) {
            // 接受两个参数
            // 参数一:最新的属性信息  属性二:最新的状态数据
            console.log(np, ns);
            // 
            if (this.state.count === ns.count) {
              return false
            }
            console.log("shouldComponentUpdate---组件是否需要更新");
            // 很重要  需要返回一个布尔值
            // true  后续更新阶段的钩子函数会执行
            // false 后续更新阶段的钩子函数不会执行 页面不会重新渲染
            // 这个方法在组件性能优化的时候使用,我们可以自行判断是否需要在页面上面展示,如果不需要可以返回false
            return true
          }
  4. Destruction phase componentWillUnmount (executed when the component is destroyed)

After 16.3, three life cycle hook functions with will are deleted

  • componentWillMount will be mounted
  • componentWillReceiveProps will receive new props
  • componentWillUpdate will update

Added lifecycle functions:

getDerivedStateFromProps is triggered when the component receives new properties, and updates the state of the component according to the current props. getSnapshotBeforeUpdate is triggered before the component is updated to ensure that the read state is consistent with componentDidUpdate

Correspondence between useEffect and class

useEffect can simulate the life cycle hook function of the component in the component defined by function. It receives two parameters: one is a callback function parameter and one can return a function. This returned method is executed when the component is destroyed

The second parameter is a dependency array. in three forms

componentDidMount, the second useEffect parameter is an empty array, then only one mount is performed during initialization

componentDidUpdate, the array in the second parameter of useEffect has data, then the callback function will be executed when each item in the array changes and the update is completed

componentWillUnmount, if parameter 2 of useEffect does not exist, the callback function will be executed every time the component is updated and will be unmounted

function Demo() {
...
React.useEffect(()=>{
  return () => {
    console.log('组件销毁的时候执行')
  }
}, [])
...
}

Why do you need to get data after the component is mounted successfully? Because the data acquisition may be asynchronous, the data acquisition is completed before the component is mounted, and the component update will be incomplete. In order to ensure the complete update of the component, the data is generally obtained after the component is mounted;

Nested component lifecycle:

The parent component's to-be-mounted and render methods will be executed, and all child components will be parsed when the render is executed. When the child components are all mounted, the mounting of the parent component will be executed.

this points to

Does this point to the problem in the component defined by the class? Why change this implementation? How to do?

Because in the component defined by the class, this points to the current instance when it is initialized. When the event is called, this has become a global value, which is null in react. In order to solve this problem, you need to change the this point in the component defined by the class. We can use three ways:

  1. Bind this to the function when the constructor is initialized (recommended, because this method is only executed once during initialization)
  2. Use arrow functions when calling assignment
  3. Bind this directly when assigning an event

Because at the time of rendering, the current this is the current component, but this no longer exists when the event response is executed.

So you need to bind this to the component defined by the class

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 this reconciliation process, React starts to re-render the entire UI interface

To change data, use the method <font color=red>**setState**</font>, setState is <font color=red>**asynchronous**</font>, and can receive two parameters, parameter one means The new data after the change; parameter 2 indicates the callback function after the data is changed, and is executed after the data is changed successfully, and parameter 2 is generally not required. You can get the latest data after the change in the callback function

setState is asynchronous, when did you encounter pitfalls?

  • setState is asynchronous, resulting in getting refs after setState will be the last value.
  • Putting it in the second callback function in setState can solve this problem.

Is setState synchronous or asynchronous?

  • Look at the specific situation:
  • First of all, if you get the state value directly after setState, you can't get it, and it is asynchronous in the native environment.
  • In asynchronous requests (ajax) or setInterval, setTimeout, setState is updated synchronously.

Execute setState twice, render several times, will it trigger immediately

Executed only once, it will not be triggered immediately, because there is a batch processing mechanism in react

React will merge setState calls into one for execution, that is to say, when setState is executed, the data in state will not be updated immediately, and will be executed in order according to first-in-first-out, but asynchronous in Ajax, setTimeout, etc. In the method, every time State is set, it will be rendered once.

What happens after calling setState?

  • After calling setState, the incoming parameters will be merged with the current state, that is, the synchronization process of real dom and virtual dom, which is the reconciliation process.
  • After the reconciliation process, react will build a new dom tree according to the latest data state in an efficient way, and then re-render the page.
  • In the process of building a new dom tree in react, local rendering will be performed according to the difference between the old and new dom, and updated on demand

Why directly modifying this.state is invalid

The essence of setState is to implement state updates through a queue mechanism. When executing setState, the state that needs to be updated will be put into the state queue, and the state will not be updated immediately. The queue mechanism can update the state in batches. If this.state is directly modified without setState, then this state will not be put into the state queue. When merging the state queue when calling setState next time, the state that was directly modified before will be ignored, so we cannot merge. And it doesn't actually update the state you want.

render method

The components defined by the class all need a render method. This method returns the DOM data displayed by the current component. This method will be re-executed every time the data or properties change.

  • Class definition components need to inherit Component

    If you use extends to implement inheritance, then in the first line of the constructor, you must call super(), super() means the constructor of the parent class

  • Each class-defined component needs a render method , which needs a return value , which returns the content of the current component

  • The component will execute this render method every time the state data or properties change

  • The state data cannot be changed in the render method

The purpose of render() in React

It is mandatory for every React component to have a **render()**. It returns a React element that is a representation of a native DOM component. If multiple HTML elements need to be rendered, they must be grouped within a single enclosing tag, eg ``, ``, ``, etc. This function must be pure, i.e. must return the same result each time it is called.

What is the difference between state and props?

- state means that the component manages data by itself, controls its own state, and is variable;

- props is the data parameter passed in from outside, immutable;

- Those without state are called stateless components, and those with state are called stateful components;

- Use more props and less state, that is, write more stateless components.

HOC

A high-order component is to pass the component as a parameter to a function and return a new component. Some other properties and methods will be added in the new component. Common advanced components are connect and withRouter

connect can map the state and dispatch in redux to the properties of the component

withRouter can add routing-related attribute information to components

- 高阶组件就是一个没有副作用的纯函数。
- 高阶组件是把一个组件当做参数,返回值为新组件的函数。
- 高阶组件实际上就是高阶函数,如 map、forEach
- 常用的高阶组件:withRouter(路由中的),connect(react-redux 中的)

The usefulness of high-order components:

- Code reuse, logic and bootstrap abstraction

- Render hijacking

- State abstraction and control

- Props control

 What are pure functions?

- Returns a new value without any side effects.

- 1. The same input always returns the same output, 2. Does not modify the input value of the function, 3. Does not depend on the external environment state. 4. No side effects.

Are reducers pure functions? Why?

- The reducer must be a pure function, and Redux only compares whether the old and new objects are the same by comparing the storage locations of the old and new objects. If you directly modify the property values ​​​​of the old state object inside the reducer, then the new state and the old state will both point to the same object. So Redux thinks nothing has changed and the returned state will be the old state.

Controlled and Uncontrolled Components

Mainly whether the value of the form is controlled by the state

Controlled components: controlled components must have value; input, textarea, select get value

Uncontrolled component: Get the value of the form through the dom element type="file"

`Controlled component` is to add `value` attribute to a form form component; `Uncontrolled component` is a component without adding `value` attribute

What are the commonly used plugins in react?

Routing, styled-components, react-redux, umi, etc.

Pass parameters between components

The props attribute is used for parent-to-child transfer, and the parent-child attribute is passed from the parent component to the child component, and the child component can receive and use it directly with props.

From child to parent using method call

Use context context or redux state management plugin between non-related components

Create a context instance through createContext, it has an attribute Provider data provider, you can set the value attribute for him. Use the Provider component to include all components, and the internal components can use the data provided in value. Use useContext inside the component to get the data value;

Why do you need to add a key when looping

Short answer:

The role of the key is to increase the speed of the diff algorithm node lookup. It is equivalent to adding a unique primary key for each node, which can quickly determine whether the current node needs to be updated;

Detailed explanation:

Keys are auxiliary identifiers used to track which elements in the list have been modified, added, or removed.

- The use of the key attribute, which involves the comparison strategy of peer nodes in the diff algorithm. When we specify the key value, the key value will be used as the id of the current component, and the diff algorithm will match according to this id. If when traversing the new dom structure, it is found that the id of the component exists in the old dom structure, then react will think that the current component has only changed its position, so it will not destroy and recreate the old component, but only change the position of the current component , and then check whether the properties of the component have changed, and then choose to keep or modify the properties of the current component.

- The key is used to distinguish the corresponding relationship between the elements in the two renderings before and after, and to prevent unnecessary update operations.

How components are optimized for performance

    1. Use memo or PureComponent keywords for optimization;

    2. Add a key for the loop;

    3. Use useCallback to optimize the function;

    4. Optimize component data and use redux to manage some global data uniformly;

    5. If it is a component defined by a class, when the updated data does not need to be displayed, it can be processed in shouldComponentUpdate;

- function定义的组件可以使用memo进行缓存操作,在组件内部使用useMemo和useCallback进行优化

- 给每一个组件包一个memo,在组件内通过useCallBack做缓存

- class定义的组件可以继承自PureComponent类

  PureComponent对属性或者状态数据进行的是浅比较,Component对属性或者数据进行的是深比较,所 以  相对来说PureComponent的性能更优,它的作用类似于function定义组件中的**memo**,可以**对组件做性能优化**。当组件接收到的属性不发生改变的话,组件不会重新渲染。建议组件定义的时候使用它

How to get the latest value in react

1. Components defined by class

   this.setState({Here is the changed data}, function() {

   ​ // Execute after the data change is successful

   })

2. Components defined by function

   You can use useEffect to get the latest value

Get dom elements in react

Use useRef in function components

In the component defined by ref class in the class component, you can get all the tags with the ref attribute set by using **refs**

Usage scenario: For example, when a picture is loaded, I want to get the width and height of the picture, and I need to use refs, such as a magnifying glass.

Similarities and differences between memo() and PureComponent components:

- Difference: React.memo() is a function component, and React.PureComponent is a class component.

- Same: Both perform a shallow comparison of the received props parameters, solve the efficiency problem of the component at runtime, and optimize the re-rendering behavior of the component.

- useMemo() is to define whether a piece of function logic is executed repeatedly.

- If the second parameter is an empty array, it will only be executed once when the component is rendered, and the update of the passed-in property value will have no effect.

  So the second parameter of useMemo() needs to pass in dependent parameters in the array.

What are the precautions for using hooks

(1)只能在React函数式组件或自定义Hook中使用Hook。
(2)不要在循环,条件或嵌套函数中调用Hook,必须始终在React函数的顶层使用Hook。
这是因为React需要利用调用顺序来正确更新相应的状态,以及调用相应的钩子函数。一旦在循环或条件分支语句中调用Hook,就容易导致调用顺序的不一致性,从而产生难以预料到的后果。
-#自定义 Hook 是一种自然遵循 Hook 设计的约定,而并不是 React 的特性。
#必须以 “use” 开头。
这个约定非常重要。不遵循的话,由于无法判断某个函数是否包含对其内部 Hook 的调用,React 将无法自动检查你的 Hook 是否违反了 Hook 的规则。
-#在两个组件中使用相同的 Hook 会共享 state 吗?
不会。自定义 Hook 是一种重用状态逻辑的机制(例如设置为订阅并存储当前值),所以每次使用自定义 Hook 时,其中的所有 state 和副作用都是完全隔离的。
#自定义 Hook 如何获取独立的 state?
每次调用 Hook,它都会获取独立的 state。

What needs to be done when the component is destroyed?

1. Clear the timer in the component

2. Cancel the unsuccessful network request

   https://www.jianshu.com/p/22b49e6ad819 An online code example for terminating network requests

redux

What is redux? Tell me about the data flow of redux?

Redux is a popular front-end development library. It is used for global state management and data manipulation. It can be used in combination with any js library (vue, Angola), etc. react is a library for the view layer, and redux is generally used in combination with react.

redux is a data management plugin. Redux uses a one-way data flow mechanism. The so-called one-way data flow is: data flows in one direction, and an action is dispatched in the view view to change the data. After the data changes, the view view is re-rendered.

Data flow in redux: dispatch an action through dispatch in the view, the reducer will receive the action, and change the data according to the type of the action. The page re-renders after the data changes. Each reducer returns a new state data;

需要注意:action必须包含一个type属性,并且不能重复。为了解决这个问题可以使用前置命名空间或者symbol这种数据类型。因为每一次dispatch派发的时候,所有的reducer都会接收到这个action,所以action的type不能重复

reducer是用来改变数据的地方,所有的数据改变都在这里。每一个reducer都需要返回一个新的state状态,在reducer中通过action的type判断以什么方式改变数据。所以action的type必须唯一,要不然就没办法区分数据怎么改变了

每一个reducer都是一个function,这个function接收两个参数(state, action),返回一个新的state状态数据

如果需要在react项目中使用redux需要使用插件react-redux

在组件中获取redux数据可以使用:useSelector或者connect实现

在组件中获取redux的dispatch方法,可以使用:useDispatch或者connect
useSelector或者useDispatch只能在function定义的组件中使用。
redux的action只能是简单的对象,如果要处理异步需要使用redux-thunk

common components, several parts

1. **Action** – Used to organize data and pass it to the reducer to perform data change operations.

   How to define action: First, it must have a type attribute, indicating the type of action being executed. They must be defined as string constants, and you can also add more properties to them

2. **Reducer** – This is where it is determined how the state will change.

   Reducers are pure functions (return a new value and have no side effects). It works by accepting the previous state and action, and returning a new object as data, the purpose is not to compare the original data, so that the performance is higher.

3. **Store** – The state/object tree of the entire program is stored in the Store.

   A Store is a JavaScript object that holds the state of the program and provides methods to access the state, dispatch actions, and register listeners. The entire state/object tree of the application is kept in a single store. Therefore, Redux is very simple and predictable. We can pass middleware to the store to process data and record various operations that change the state of the store. All operations return a new state via reducers.

4. **View** – Only display the data provided by the Store.

Its workflow is to dispatch an action through dispatch in the page, and change the data after receiving the action in the reducer. The page is re-rendered after the data changes.

Redux usage process

- Install react-redux in scaffolding

- Use createStore to create a global store to save all states. createStore receives a reducer as a parameter, and you can use combineReducers to pass in multiple reducers.

- In the reducer, two parameters are received, the first parameter indicates the initial state of the data, the second parameter indicates the action, and the reducer will return a new object as data, so that the comparison of the original object is not required, and the performance will be improved improve.

- If you want to change the data, the view dispatches an action to execute the corresponding reducer through dispatch, and updates it in the store. If the store changes, the view will re-render.

- We may use the connect and Provider methods in react-redux to associate our data. Provider provides store to subcomponents through context context, and connect associates data in redux with props in components. The method used here is mapStateToProps to map data in store to props of components, so that it can be used in components Access the data in redux through props.

- If you need to send asynchronous requests, you also need the react-thunk plug-in, which needs to be configured in creaceStore.

Flux

Flux is an architectural pattern that enforces unidirectional data flow. It controls derived data and enables communication between multiple components using a central store with authority over all data. Data updates throughout the application must only occur here. Flux provides app stability and reduces runtime errors.

The action in redux must be a plain object (simple object), not a function. In order to solve the problem of asynchronous action, we need to use plugins

The function of the redux-thunk plug-in is to determine what type of action our dispatch is currently in. If it is an object, it will be executed directly; if it is a function, dispatch will be dispatched inside the function passed as a parameter.

The principle of redux middleware

- Middleware is actually a modification of dispatch

- Middleware refers to the modification of dispatch between action and store

- When dispatching an action, go to the middleware first, and then go to the store

- From action (middleware) -> store -> reducer -> store

[redux-toolkit](https://redux-toolkit.js.org/)

It is a redux plug-in set provided by the official, which allows us to use redux for development in the project very conveniently, without additional configuration. It has built-in some commonly used plug-ins, such as: dev-tools (developer debugging tools), redux-thunk (handling asynchronous operations), immutable (immutable data types), etc.

npm install @reduxjs/toolkit react-redux # 安装依赖

createSlice

The role of this API is to create each reducer data, organized by specifying name, initialState, reducers and extraReducers

- name represents the namespace

- initialState represents the initial value

- The way of changing data defined by reducers can be directly exported as actions

- extraReducers listens to other reducers, not synchronously changing data operations in the current slice

configStore

The role is to configure or create a store data source

createAsyncThunk

The function is to create an asynchronous action, which will have three states after the creation is successful

pending, in progress

rejected, failed

fulfilled, successful. It receives two parameters, the first parameter is the current state data, and the second parameter is the action

Three principles followed by redux

#单一数据源
整个应用的 state 被储存在 一棵 object tree 中,并且这个 object tree 只存在于 唯一一个 store 中。
#状态(State) 是只读的
唯一改变 state 的方法就是触发 action。
这样确保了 视图 和 网络请求 都不能直接修改 state,相反它们只能表达想要修改的意图。因为所有的修改都被集中化处理,且严格按照一个接一个的顺序执行,因此不用担心 竞态条件的出现。
#使用纯函数来修改state
为了指定状态树如何通过操作进行转换,你需要纯函数。纯函数是那些返回值仅取决于其参数值的函数。

Redux advantages:

- **Predictability of results-** Since there is always one source of truth, the store, there is no question of how to synchronize the current state with actions and other parts of the application.

- **Maintainability-** Code becomes easier to maintain, with predictable results and strict structure.

- **Server-side rendering-** You only need to transfer the store created on the server to the client. This is useful for initial rendering and optimizes app performance for a better user experience.

- **Developer Tools-** From actions to state changes, developers can track everything happening in the app in real time.

- **Community and Ecosystem -** Redux has a huge community behind it which makes it even more fascinating. A large community of talented individuals has contributed to library improvements and developed various applications.

- **EASY TO TEST-** Redux's code is mostly small, pure and self-contained functions. This makes the code testable and self-contained.

- **Organization -** Redux explains exactly how code is organized, which makes code more consistent and simple when used by teams

Disadvantages of redux:

- The data required by a component must be passed from the parent component, and cannot be directly fetched from the store like in flux.

- When the related data of a component is updated, even if the parent component does not need to use this component, the parent component will still re-render, which may affect efficiency, or need to write complex shouldComponentUpdate for judgment.

Data management in redux

Will you manage the data uniformly in redux, or manage the shared data in redux?

- All data should be managed in redux.

- When a component has both state and props and redux storage to store data. A component has two to three hundred lines, and I don’t know where to check for errors, which is not easy to maintain.

- When the business logic needs to be expanded, the data is stored in the state. When other components need your data, it will be very troublesome. Redux is more convenient.

- Don't worry about redux consuming memory, redux memory is 5 G (chrome browser)

Can the type of action in redux be the same? Why? How to solve?

Cannot be repeated. Because every time an action is dispatched, all reducers will receive this action. If the type of the action is the same, then there is no way to distinguish which one made the change. Namespace can be set for type, for example: "xx/type", xx means clear space, type means action type, so that they can be distinguished. Or use the symbol type to define. Be sure to ensure that the type of action is not repeated

What are the ways to get the data in the state in redux?

connect 和 useSelector

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

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

The difference between onclick in js native event and onclick in jsx

The onclick event processing function in native js is executed in the global environment, which pollutes the global environment, and adds onclick events to many dom elements, which affects the performance of the web page. At the same time, if the element is dynamically deleted from the dom tree, it must be manually logged out Event handler, otherwise it may cause memory leaks;

The functions mounted by onClick in jsx are all controlled within the scope of the component and will not pollute the global space. Instead of using onclick directly in jsx, it adopts the method of event delegation to mount the topmost DOM node, and all click events are captured by this event. , and then assign it to a specific function according to the specific component. Of course, the performance is higher than mounting an event processing function for each onClick. In addition, React controls the life cycle of the component. When unmounting, it is natural to be able to clear all related event processing functions and memory. Leakage is no longer an issue;

single stream

The unidirectional data flow method uses an upload data flow and a downlink data flow for two-way data communication, and the two data flows are independent of each other. Unidirectional data flow means that the state can only be modified in one direction.

advantage:

1. All state changes can be recorded and tracked, and the source is easy to trace;

2. There is only one copy of all data, and only one entry and exit for component data, which makes the program more intuitive and easier to understand, and is conducive to the maintainability of the application;

3. Once the data changes, update the page (data-page), but not (page-data);

4. If the user makes a change on the page, it will be collected manually (two-way is automatic) and merged into the original data.

shortcoming:

1. The HTML code rendering is completed and cannot be changed. If there is new data, the old HTML code must be removed, and the new data and template must be integrated to render again;

2. The amount of code increases, the data flow process becomes longer, and many similar boilerplate codes appear;

Virtual dom and diff algorithm

Virtual dom is a dom tree structure expressed by js, which will eventually generate real dom. It is a js object, so the efficiency of update comparison is very high. When rendering and generating the real dom tree, it will perform partial update instead of updating the entire page. This is convenient for improving page rendering speed and optimizing page performance

The diff algorithm is a comparison algorithm, which is used to compare the changes of the virtual dom. Find which position has changed and perform a replacement operation. It is compared layer by layer, and directly replaces the entire tree when encountering a changed node;

diff algorithm

Calculate the real changed part of the virtual DOM, and only perform native DOM operations on this part instead of re-rendering the entire page.

(1) What is reconciliation?

The minimal manipulation process of converting a virtual DOM tree into a real DOM tree is called reconciliation.

(2) What is the React diff algorithm?

The diff algorithm is the specific implementation principle of reconciliation:

- Decompose the tree structure according to the level, and only compare elements of 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 (the class here refers to the name of the component)

- Merge operation, when calling the component's setState method, React marks it as dirty. At the end of each event loop, React checks all components marked dirty and repaints.

- Selective subtree rendering. Developers can override shouldComponentUpdate to improve the performance of diff.

virtual dom

- The virtual dom is actually a js object. It is a manifestation of the real dom in memory. The virtual dom and the real dom are synchronized. This synchronization process is the reconciliation process.

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

- When comparing the real dom, it is very complicated. There will be methods, attributes, and events on the real dom tree, which will consume a lot of performance. By converting real dom objects into objects in js, it does not have the characteristics of real dom, and simply comparing the performance of js objects will be faster.

Error boundaries in react? React captures page render exceptions

- The concept of Error Boundaries was introduced in React16.X.

- It can catch errors generated in its subcomponents, similar to try-catch, but implemented in the form of react components.

- With the error boundary, even if the result of a certain component is wrong, the entire React program will not be hung up. Only the component that failed displays a fallback interface, while the entire program remains fully functional.

- The componentDidCatch() function here is similar to the catch {} code block in JavaScript, but it can only be used for components. Only class components can be error boundaries.

- Inside the componentDidCatch() function we set the hasError state to true. Then check that state in the render method. If the error status is true, render the fallback interface; if it is false, render the React component interface you want to render as a subcomponent interface.

Nevertheless, the following errors Error Boundaries still cannot be caught:

- event error

- Error Boundaries itself

- asynchronous code

Controllable and Uncontrollable Components

- The core difference between controllable components and non-controllable components is whether the input value corresponds to the state value

- Non-controllable components need to use ref to get the value from the dom node when getting the value

- Mainly whether the value of the form is controlled by the state

- You need to monitor onChange yourself and update the state

what is reselect

- Similar to the computed property in vue

- derived data

- There is a cache of values ​​for performance optimization

ref and refs

- ref is used to get the dom element

- Refs is shorthand for references in React. It is a property that helps to store a reference to a specific React element or component, which will be returned by the component render configuration function. Used for a reference to a specific element or component returned by render(). You need refs when you need to do DOM measurements or add methods to components.

  When using refs:

  - When you need to manage focus, select text or media playback

  - Triggered animation

  - Integrate with third-party DOM libraries

- For example, when a picture is loaded, if I want to get the width and height of the picture, I need to use refs, such as a magnifying glass.

two

The dva framework is essentially a set of frameworks encapsulated by Ant Financial based on the React technology stack.

The feature is that it eliminates the trouble of manually building a complete development environment (installation of Redux, React-Router, etc.) for novices. One-click installation is enough for project development. Although it reduces the difficulty of getting started, it inevitably makes the expansion cost more expensive. High (for example, if you need to configure specific webpack configuration items separately, and these configuration items are not in the configurable range of roadhog), there is no need to worry. Web applications with low system complexity are developed using the dva framework, and it is more than enough to use packaged configuration items.

Register the model into the dva instance. Use the connect function in the page to connect the redux store and page components, and pass the state in the store into the page component as props. And initiate an asynchronous request to obtain remote data after the component is successfully mounted. Write the reducer corresponding to this action and the asynchronous action that initiates the asynchronous request.

What is the difference between hybrid events in react and native dom events

Events in react are processed by the framework for secondary encapsulation, which is different from native dom events. They are not added directly on dom elements

The DOM event model is divided into capturing and bubbling. When an event occurs, it propagates between child and parent elements. Event propagation is divided into three phases:

Capture (Capture): The process of passing the event object from the window object to the target object.

Target: The target node is processing the event.

Bubble: The process of passing the event object from the target object to the window object.

The event mechanism in React is completely different from the native one. The event is not bound to the native DOM, and the emitted event is also a wrapper for the native event. React's internal event system can be divided into two phases: event registration and event triggering.

Event registration: React registers all DOM events to the document node.

Event triggering: When the event is executed, the binding event on the document will distribute the event, and find the component that triggered the event according to the previously stored type and component ID.

Advantages of React event mechanism:

1. Reduce memory consumption and improve performance. An event type is only registered once on the document

2. Unify the specification, solve the compatibility problem of ie events, and simplify the event logic

3. Friendly to developers

webpack


webpack

Front-end modular development packaging tool, its main goal is to package JavaScript files together, we have always used it, but I checked the documentation for all configurations.

In webpack, is the conversion of JSX completed with the help of loader? Or babel?

Because the code of react cannot be run directly in the browser, it can be run in the browser only by converting the code into ES5 with the help of scaffolding. (In vue, it is transformed with the help of vue-loader in webpack) react uses babel Converted by preset-react in.

webpack packaging principle

Packing principle: webpack treats the project as a whole. With a given main file, webpack will find all the dependent files in your project from this main file, use the loader to process them, and finally pack them into one or more js file recognized by the browser

Basic functions and working principles of webpack

1. Code conversion: compile TypeScript into js, ​​compile scss into css, etc.

2. File optimization: compress js, css, HTML code, compress and merge pictures, etc.

3. Code segmentation: extract the common code of multiple pages, extract the code that does not need to be executed on the first screen, and let it load asynchronously

4. Module merging: A module refers to other modules and files, and it needs to build a function to merge the modules into one file

5. Hot update: monitor local original code changes, automatically build and update content

webpack configuration, webpack.config.js

const path = require("path"); //引入path
module.exports = {
  entry: "./path/to/my/entry/file.js", //入口路径,从哪开始打包
  output: {
    path: path.resolve(__dirname, "dist"), //__dirname指webpack.config.js所在的目录,dist指输出路径
    filename: "my-first-webpack.bundle.js", //输出文件名
  },
};
  • mode: 'development' development mode
  • entry
    • The entry path tells webpack where to start packaging
  • output
    • The output  attribute tells webpack where to output the  bundles it creates , and how to name those files.

code management tool git


Please refer to previous articles: http://t.csdn.cn/cuIdz

Guess you like

Origin blog.csdn.net/leoxingc/article/details/127857631