Websocket usage problem
Websocket protocol and HTTP protocol are located in the network application layer, are application layer protocol, and TCP is located in the transport layer, belong to the transport layer protocol, and WS and HTTP are based on TCP implementation of the upper layer protocol, and HTTP is different from HTTP, WS can make the client (broad client, Including the browser) and the server to establish a long link full duplex communication channel, not only so that the client can actively send messages to the server, but also so that the server can actively send messages to the client, because it is a long link channel, each message will not repeatedly create and destroy links.
The first step of establishing a WS link is achieved by means of the HTTP protocol, followed by the real WS link
Note a few special HTTP headers:
- Connection: Upgrade // Tells the server that this link is for a protocol Upgrade. In fact, this header is used more often than not, and TA has the famous keep-alive value
- Upgrade: websocket // Tells the server to Upgrade to the Websocket protocol
- Sec-WebSocket-Extensions: permessage-deflate; Client_max_window_bits // Protocol extension type
- Sec-websocket-key: IhTmM/PyVb55uCkAU5Iw1Q== // This Key is transmitted to the server
- Sec-websocket-version: 13 // WebSocket Version supported by the client
- After obtaining sec-websocket-key, add “258eAFa5-E914-47DA-95CA-C5AB0DC85b11” to the end and then use SHA1 algorithm to generate a result, and then base64. It is returned to the client as the value of SEC-websocket-Accept. After receiving the HTTP Response, the client also calculates the final Base64 according to the same algorithm and compares it with the value of SEC-websocket-Accept returned by the server. If they are the same, the verification succeeds.
Websocket security problem
Authentication is performed based on the password token negotiated between the server and client
What happens after the HTTPS request
Reference: fecommunity. Making. IO/front – end – I…
Three handshakes and four waves
Reference: juejin. Cn/post / 684490… The function of three-way handshake: 1. Confirm whether the reception ability and sending ability of both parties are normal. 2. Specify your own initialization sequence number in preparation for subsequent reliable delivery. 3. If HTTPS protocol is used, the three-way handshake process will also carry out the verification of digital certificate and the generation of encryption key to.
4. Brief description of CSRF (Cross-site Request Forgery) attack and Defense measures (CSDN Blog -CSRF)
Tech.meituan.com/2018/10/11/… Blog.csdn.net/stpeace/art…
5. React fiber usage
Fiber is for finer control of the rendering process. Fiber architecture core: interruptible, Recoverable, and Priority.
6. React composite events
React is a custom event object that smooths out browser differences at the bottom and exposes developers to a unified, stable event interface that is identical to DOM native events at the top. React uses the React event system to handle events. For example, the setState batch update will enable isBatchingUpdate = true in the synthesized event. Set isBatchingUpdate to false using transaction close. Although the synthesized event is not a native DOM event, it retains a reference to the native DOM event. When you need access to a native DOM event object, you can get it from the synthesized event object’s E.ativeEvent property
8. Webpackage 5 knowledge
10. The understanding of the node
Reference: segmentfault.com/a/119000002…
React to the new life cycle
React (15-16.3) before a special: old componentWillReceiveProps (newProps) [do not perform for the first time, after no matter whether there is a new props, will update 】
React (after 16.4) static getDerivedStateFromProps(nextProps, NextState) getSnapshotBeforeUpdate() can capture some information from the DOM (such as scroll position) before possible changes, return value)
let ThemeContext = React.createContext(null); / / the parent component let contextVal = {changeColor: this.changeColor, color: this.state.color}; <ThemeContext.Provider value={contextVal}> <div style={{ margin: '10px', border: `5px solidThe ${this.state.color} `,padding: '5px', width: 200}} > page <Header /> <Main /> </div> </ThemeContext.Provider> / / child component <ThemeContext.Consumer> { (value) => ( <div style={{ border: `5px solidThe ${value.color} `,margin: '5px', padding: '5px' }}> main <Content /> </div>)}</ThemeContext.Consumer> Copy the code
React-hooks (after 16.8) useAPI
12. Page loading performance optimization
Reference segmentfault.com/a/119000002…
- Related to the react
- Use shouldComponentUpdate to circumvent redundant update logic
- PureComponent + Immutable.js
- The React. Memo and useMemo useCallback
- Use the useMemo return component instead of react.Memo
- Network dependent
- Reducing HTTP requests
- Use server-side rendering
- Static resources use CDN or are placed on Nginx
- Make good use of caching and do not load the same resource twice
- Picture-dependent
- Image lazy loading (native support lazy loading API, very useful)
- Reduced image quality (JPG is smaller than PNG, image quality is compressed)
- Use the font icon iconfont instead of the image icon (Ali icon library directly generates the font icon)
- Zoom in and out with SVG without distortion
- Webpack related
- Use urL-loader to transfer the image to base64
- Use externals to import the JS library
- Js language dependent
- Place the CSS at the top of the file and the JavaScript file at the bottom
- Use switch instead of if-else
- The compressed file
- Avoid page stalling (fiber sharding, timer sharding)
- Use requestAnimationFrame to implement visual changes
- Use as operation
- DOM related
- Reduce redraw backflow
- Use event delegates to save memory
- CSS related
- Reduce the complexity of CSS selectors
- Use Flexbox instead of the earlier layout model
- Animating is implemented using the transform and opacity property changes
React, map, and Key functions
Keys are an auxiliary identifier used by React to track which elements in a list were changed, added, or removed.
In the React Diff algorithm, React uses the Key value of an element to determine whether the element is newly created or moved, thus reducing unnecessary element re-rendering.
The Diff algorithm
- The key point of Diff algorithm performance breakthrough lies in “hierarchical comparison”;
- Nodes of the same type are necessary to continue Diff;
- The key attribute is set to help us reuse as many nodes as possible within the same hierarchy.
14. The difference between class components and function components
As components, class components and function components do not differ in how they are used or rendered, nor do they differ significantly in performance in modern browsers. They have very different mental models at the time of development. Class component is based on object-oriented programming, it is the main inheritance, life cycle and other core concepts; The functional component kernel is functional programming, which is immutable, has no side effects, transparent reference, and so on. Previously, in the usage scenario, if there is a component that needs to use the life cycle, then the class component is promoted; Design patterns, if inheritance is needed, push the class component. But now function components can completely replace class components thanks to React Hooks, which have made life cycles obsolete. Secondly, inheritance is not the best design mode for components. The official advocates the design concept of "combination is better than inheritance", so the advantages of class components in this aspect are fading out. In terms of performance optimization, the class component mainly relies on shouldComponentUpdate to block rendering to improve performance, while the function component relies on react.Memo to cache rendering results to improve performance. Class components are much easier to learn, but function components are the future of the community thanks to React Hooks. Class components are not easy to optimize in the future time slice and concurrent mode due to the complexity of the life cycle. The function component itself is lightweight and simple. Based on Hooks, it provides more fine-grained logic organization and reuse than the original, and can better adapt to the future development of React.Copy the code
15. Why react-hooks are needed
- Say goodbye to the incomprehensible Class;
- Solve the problem that business logic is difficult to split;
- Making state logic reuse simple and feasible;
- Function components are more in line with React concept in terms of design.
16. UseState useMemo, useCallback, useReducer implementation
let hookStates = [];
let hookIndex = 0;
/ / useState implementation
function useState(initialState) {
hookStates[hookIndex] =
hookStates[hookIndex] || typeof initialState === 'function' ? initialState() : initialState;
let currentIndex = hookIndex;
function setState(newState) {
hookStates[currentIndex] = newState;
render();
}
return [hookStates[hookIndex++], setState];
}
/ / useMemo implementation
function useMemo(factory, deps) {
if (hookStates[hookIndex]) {
let [lastMemo, lastDeps] = hookStates[hookIndex];
let same = deps.every((item, index) = > item === lastDeps[index]);
if (same) {
hookIndex++;
return lastMemo;
} else {
let newMemo = factory();
hookStates[hookIndex++] = [newMemo, deps];
returnnewMemo; }}else {
let newMemo = factory();
hookStates[hookIndex++] = [newMemo, deps];
returnnewMemo; }}/ / useCallback implementation
function useCallback(callback, deps) {
if (hookStates[hookIndex]) {
let [lastCallback, lastDeps] = hookStates[hookIndex];
let same = deps.every((item, index) = > item === lastDeps[index]);
if (same) {
hookIndex++;
return lastCallback;
} else {
hookStates[hookIndex++] = [callback, deps];
returncallback; }}else {
let newMemo = factory();
hookStates[hookIndex++] = [callback, deps];
returncallback; }}/ / useReducer implementation
function useReducer(reducer, initialState, init) {
hookStates[hookIndex] = hookStates[hookIndex] || (init ? init(initialState) : initialState);
let currentIndex = hookIndex;
function dispatch(action) {
hookStates[currentIndex] = reducer ? reducer(hookStates[currentIndex], action) : action;
render();
}
return [hookStates[hookIndex++], dispatch];
}
//useState is a simplified version of useReducer, which is a syntax sugar
function useState(initialState) {
return useReducer(null, initialState);
}
// useContext implementation, useContext and useReducer combined use
let CounterContext = React.createContext();
export default function App() {
let [state, dispatch] = React.useReducer(reducer, { number: 0 });
let value = { state, dispatch };
return (
<CounterContext.Provider value={value}>
<Counter></Counter>
</CounterContext.Provider>
);
}
function useContext(context) {
return context._currentValue;
}
function Counter() {
let { state, dispatch } = useContext(CounterContext);
return (
<div>
<p>{state.number}</p>
<button onClick={()= > dispatch({ type: 'ADD' })}>+</button>
<button onClick={()= > dispatch({ type: 'MINUS' })}>-</button>
</div>
);
}
/ / useEffect implementation
function useEffect(callback, deps) {
// will be re-rendered
if (hookStates[hookIndex]) {
let lastDeps = hookStates[hookIndex];
let same = deps.every((item, index) = > item === lastDeps[index]);
if (same) {
// If the dependency array is the same as the last dependency array
hookIndex++;
} else {
hookStates[hookIndex++] = deps;
setTimeout(callback); }}else {
hookStates[hookIndex++] = deps;
setTimeout(callback); // Simulate a macro task to ensure that the callback is executed after the page is rendered}}function render() {
hookIndex = 0;
ReactDOM.render(<App />.document.querySelector('.root'));
}
Copy the code
17. Unique use method of useMemo
Use useMemo return function components instead of React. The memo and zhuanlan.zhihu.com/p/348796468 useCallback reference
import { useEffect, useState, memo, useCallback, useMemo } from 'react';
import ReactDOM from 'react-dom';
import React from 'react';
function Child({ onButtonClick, data }) {
console.log('Child render');
return <button onClick={onButtonClick}>{data.number}</button>;
}
// Child = memo(Child);
function App() {
const [number, setNumber] = useState(0);
const [name, setName] = useState('zhufeng');
const addClick = useCallback(() = > setNumber(number + 1), [number]);
const data = useMemo(() = > ({ number }), [number]);
let a = useMemo(() = > <Child onButtonClick={addClick} data={data}></Child>, [number]);
return (
<div>
<input type="text" value={name} onChange={(e)= > setName(e.target.value)} />
{a}
</div>
);
}
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
Copy the code
18. Understand the story
-
Redux consists of three parts: Store, Reducer, and Action.
- Store: It is a single data source and is read-only.
- I’m going to take Action. I’m going to take Action.
- Reducer is a function that distributes and processes changes and ultimately returns new data to the Store.
-
The main API
- getState
- subscribe
- dispatch
- createStore
19. The TypeScript
Template, Interface, Enumeration (enum)
20. What is a pure function
/** Pure function (no side effects) 1. Same argument returns same result 2. You cannot modify variables */ that are out of scope
function sum(a,b){return a+b};
function sum2(a,b){window.a='c'; return a+b};
Copy the code
What about HTTP caching? (Interview highlights)
Reference: fecommunity. Making. IO/front – end – I… www.cnblogs.com/wonyun/p/55… Http caching mainly uses cache-control and ETag in the header
- Cache-control
If no-cache is set to cache-control, the browser will verify that the Cache is expired every time a resource is used. If cache is used directly, return code: 304- Cache location 2. Cache time 3. Reverify
- ETag is used for comparison caching. ETag is an IDENTIFIER of the server resource. When the client sends the first request, the server sends the identifier of the current requested resource ETag. The client uses if-none-match in the header to Match the Etag. The server compares the Etag sent by the client with the latest resource Etag. If the same, the resource is not updated and 304 is returned.
- Caching scheme
-
Resource verification How to verify whether a resource has expired:
Last-modified (Last Modified time)
Used with if-modified-since or if-unmodified-since If a last-modified header is in the requested resource header, the header specifies a time. The browser reaccesses the resource with the if-modified-since header, which is the last-modified time. The server compares this time with the Last Modified time and tells the browser whether it can use the resource directly. Etag (Data signature)
The resource generates a unique data signature based on its content, and if the resource is updated, the Etag changes. Used with if-match or if-none-match
Difficulties encountered in the project
1. The structure of ANTD3 and ANTD4DOM is different, and the theme color cannot be configured in the external import library of single-SPA. 2. The amount of data transmitted by websocket is too large, resulting in lag. Use the commend of spread-js to reduce transmission. 3. OCR recognizes the picture in the document. If the file is too large, use the file service to upload the picture to CDN and request the picture address.