Can a React Class component request be initiated in componentWillMount? Why is that?
No, need to handle in componentDidMount hook
Depending on the situation, if the server render will not get the data.
The componentWillMount method is called after constructor and before Render. Calling setState in this method does not trigger a rerender, so it is not typically used to load data and is rarely used.
Most of the data fetched from the background is related to the data being loaded on the component, so it’s done in the componentDidMount method. Loading independent of data on a component can also be done in constructor, but constructor is used to initialize component state and is not designed to load data, so any code with side effects is concentrated in the componentDidMount method.
React Class and React Hook.
Hook 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.
In the original code, we used HOC/render/Props to reuse the state of the component and to enhance functions, which increased the number of layers in the component tree. In React Hooks, these functions are implemented using powerful custom Hooks.
The Hooks component makes react development easier to use, allowing beginners to develop projects without using the class component.
The advantages of Hooks:
- React Hooks code is more readable. Hooks can split class components into function code groups in different lifecycle functions for easy maintenance;
- Hooks component is less difficult to develop
High-order functions and custom hooks in React 【👉🏻 hooks 】
Higher-order components are essentially passing in a component as an argument and returning a new component. Business overencapsulation of higher-order components can lead to deeper nesting of component levels.
Custom Hook can be reused without using higher-order components.
UseState works in React Hook.
UseState returns a stateful value and a function to update it. During initial rendering, the state returned (state) is the same as the value passed as the first parameter (initialState). The setState function is used to update the state. It accepts a new state value and queues up to re-render the component. During the update process,
- First render, render()
- Render calls the App function to get the virtual DIV and create the real DIV
- The user clicks on the Button, calls setN(n+1), and the render function is called again
- Render further calls the App function to get the virtual DIV, Diff, and update the real DIV
- Each time setN calls Render again, which in turn calls App
The realization of useState and useEffect
5.1 Implementation of useState and useEffect
import React from "react";
import ReactDOM from "react-dom";
let val;
function useState(initVal) {
val = val || initVal;
function setVal(newVal) {
val = newVal;
render(); // Rerender the page
}
return [val, setVal];
}
Copy the code
// Custom useEffect
let watchArr;
function useEffect(fn, watch) {
consthasWactchChange = watchArr ? ! watch.every((val, i) = > val === watchArr[i])
: true;
if(hasWactchChange) { fn(); watchArr = watch; }}Copy the code
Cause analysis of variable conflictuseState
For example:
- All calls
useState
Method all ** share a global variableval
. - Therefore, multiple calls in a component can cause variable conflicts.
5.2 Resolve variable conflicts
Above, we have implemented the useState and useEffect functions and called them successfully, but the above cases are all in the case of one variable, so if there are two variables, still use the above custom code, what will happen?
Code improvements:
- Variables are maintained through a global array.
- A global subscript is used to locate the location of the corresponding state variable.
import React from "react";
import ReactDOM from "react-dom";
let memoizedState = [];
let currentIndex = 0;
function useState(initVal) {
memoizedState[currentIndex] = memoizedState[currentIndex] || initVal;
const cursor = currentIndex;
function setVal(newVal) {
memoizedState[cursor] = newVal;
render();
}
// Return state and then currentIndex+1
return [memoizedState[currentIndex++], setVal];
}
// Custom useEffect
function useEffect(fn, watch) {
consthasWatchChange = memoizedState[currentIndex] ? ! watch.every((val, i) = > val === memoizedState[currentIndex][i])
: true;
if (hasWatchChange) {
fn();
memoizedState[currentIndex] = watch;
currentIndex++; / / accumulative currentIndex}}function App() {
const [count, setCount] = useState(0);
const [data, setData] = useState(0);
useEffect(() = > {
console.log('Custom useEffect call --count:${count}`);
}, [count]);
useEffect(() = > {
console.log('Custom useEffect call --data:${data}`);
}, [data]);
return (
<div>
<button onClick={()= >{ setCount(count + 1); }}> {' button 1: current clicks: ${count} '}</button>
<hr />
<button onClick={()= >{ setData(data + 1); }}> {' button 2: current clicks: ${data} '}</button>
</div>)}// first render
render();
function render() {
console.log(memoizedState); // Execute the hook to change the array
currentIndex = 0; // Set to 0 when rerender
ReactDOM.render(<App />.document.getElementById("root"));
}
Copy the code
From the above code, we can see that every time the render() function is called, the corresponding global subscript is reset to 0. This operation was strange to me when I first saw it, and it took me a while to understand why:
Because we store the variables in an array according to the order in which the hooks are called.
The second argument to our useEffect function is an array, because our variable storage is also an array.
Note: our code here is a simplified version, the official useState and useEffect functions will definitely be improved. I want you to differentiate.
6 Use useCallback to optimize performance when React binds events
A React component, such as an onClick={fn} event, would generate a new fn function every time render, resulting in waste of resources.
In daily development, we often add an onChange or onClick event to a button, so take the onClick event as an example:
- If button A is bound to the onClick event, it must be calling our custom onClick function.
- We triggered the rendering of the component due to some other component, so every time we render, the new onClick function will be regenerated.
- This leads to unnecessary rendering and wasted performance.
The pseudocode is as follows:
class Demo extends Component{
render() {
return
<div>
<Button onClick={() = >{console.log('Hello World!! '); }} / ></div>; }}Copy the code
Therefore, when developing class-based components, we often rewrite code like this to avoid wasting performance:
class Demo extends Component{
constructor(){
super(a);this.buttonClick = this.buttonClick.bind(this);
}
render() {
return
<div>
<Button onClick={ this.buttonClick} / >
</div>; }}Copy the code
So what if you’re developing in functional components?
Answer: Use the useCallback() function in ReactHook:
function Demo(){
const buttonClick = useCallback(() = > {
console.log('Hello World!!!!! ')
},[])
return(
<div>
<Button onClick={ buttonClick} / >
</div>)}Copy the code
UseEffect (side effect Hook) description and use
[useEffect to isolate side effects]
The Hook receives a function that contains imperative code that may have side effects.
Changing the DOM, adding subscriptions, setting timers, logging, and performing other side effects within the body of a function component (in this case, during the React rendering phase) are not allowed, as this can cause unexplained bugs and break UI consistency. Use useEffect for side effects. The function assigned to useEffect is executed after the component is rendered to the screen. You can think of Effect as an escape route from the purely functional world of React to the imperative world. (Official document)
We will also initiate requests in useEffect.
TIPS:
You can think of useEffect Hook as a combination of componentDidMount, componentDidUpdate, and componentWillUnmount.
How do I use useEffect
Implement componentDidMount (second parameter is [])
UseEffect’s second argument is an empty array that is not executed after an initial call, equivalent to componentDidMount.
ComponentDidMount componentDidUpdate componentDidMount componentDidUpdate
When useEffect has no second argument, the initialization and update of the component are performed.
7.3 Implementing the function of combining componentDidMount componentWillUnmount
UseEffect returns a function that is executed when the component is uninstalled
useEffect(() = > {
const id = setInterval(() = > {
setCount(c= > c + 1);
}, 1000);
return () = > clearInterval(id); } []);Copy the code
React how to detect rerender, what causes rerender, and how to avoid rerender?
A: When the internal data changes, the state changes (by calling this.setstate ()), and the props passed by the parent component changes, it causes the component to re-render.
React to have such a hook in the life cycle, called shouldComponentUpdate function, is a heavy rendering render () function call before the called function, two parameters nextProps and nextState, said the next props and the value of the state. When the function returns false, it blocks the subsequent render() call, preventing the component from rerendering, and when the function returns true, the component renders as usual. SetState without changing the value of state and rerendering the parent component with no data exchanged will both result in rerendering the component, but we can prevent both with shouldComponentUpdate. ShouldComponentUpdate is not perfect. Consider immutable.js (the principle is to return the same reference for invariant objects and a new reference for changed objects) or the PureRenderMixin plug-in.
9 How does useState initialize data in React?
A function component that will be called when react renders, so useState will be called every time. UseState is implemented differently in different phases. In the onMount phase, state is initialized. In the onUpdate phase: Update state. UseState returns an array, and the second item in the array is a function that triggers a React update each time it is called
##### What do you use to optimize React performance?
A:
- Use shouldComponentUpdate to circumvent redundant update logic
- PureComponent + Immutable.js
- The React. Memo and useMemo
Brief description of Vue 2.x full link operation mechanism?
A:
- Initialize and mount init, mount
- After compiling template, compile template into render function
- Render function => VNode tree
- Render function => getter, setter => watcher.update => patch And a strategy to use queues for asynchronous updates.
- Finally, patch update view is carried out after diff algorithm
What are the ways to communicate across components in Vue?
A:
- Father-son communication:
The parent passes data to the child through props, and the child passes data to the parent through events (emit). Can also communicate via parent/child chain (EMIT); Can also communicate via parent/child chain (EMIT); Communication is also possible through parent/child chains (parent/children); Ref can also access component instances; Dojo.provide/injectAPI; The children); Ref can also access component instances; Provide/inject API; The children); Ref can also access component instances; Dojo.provide/injectAPI; attrs/$listeners
- Brothers:
Bus; Vuex
- Cross-level communication:
Bus; Vuex; Dojo.provide/inject API, attrs/attrs/attrs/listeners
How does responsive data in Vue listen for the deep properties of an object?
A:
Use watch with deep:true to implement deep listening on objects
What is the difference between MVVM, MVC and MVP? What are their application scenarios?
- MVC is a pattern for creating Web applications using MVC (Model View Controller model-View-Controller) design.
- Low coupling
- High reusability
- Low lifecycle cost
-
MVP evolved from the classic pattern MVC. Their basic ideas have the same place Controller/Presenter is responsible for logic processing, Model provides data, and View is responsible for display.
-
MVVM is essentially an improved version of MVC. MVVM abstracts the state and behavior of the View in it, and lets separate the View UI from the business logic.
- Low coupling
- reusability
- Independent development
- testable
MVVM is characterized by data-binding: Changes to the View are automatically reflected in the View Model and vice versa. Instead of having to deal with receiving events and View updates, the framework does it for you.
What is the difference between Loader and Plugin in Webpack?
A:
In Webpack, Loader is responsible for completing the loading of various resource modules in the project, so as to realize the modularization of the overall project, while Plugin is used to solve other automation work in the project except the packing of resource modules. In contrast, Loader only works in the loading link of modules. Plug-ins can touch almost every aspect of Webpack’s work.
What is the role of Git Hook in a project?
A:
Git Hooks are custom scripts, so they implement functions that are dependent on the corresponding Git actions. Here are a few simple examples:
- Multiple development code syntax, mandatory uniform specifications
- Commit Message formatting and whether it conforms to a specification
- Test case detection if required
- All development members are notified of new updates to the server code
- Automatic project packaging after code submission (after Git Receive)
- And so on…
##### why is HTTPS more secure than HTTP?
A:
HTTPS ensures transmission security, preventing the transmission process from being monitored and data from being stolen. You can verify the authenticity of the website (details will be discussed in a second interview). However, it is important to note that packets can still be captured using HTTPS, because HTTPS only prevents users from having their communications monitored without their knowledge. If users initiate the trust, it is possible to build a “man-in-the-middle” network, where proxy software can decrypt the content of the transmission
eighteen
nineteen
twenty
reference
- Simple implementation of React hooks useState useEffect
conclusion
- It is recommended to use useCallback to write event callbacks. The dependency arrays must be empty. []
- Purpose: The useCallback function generates a memory function that can be updated without rendering the function. Thus achieving the goal of avoiding performance waste.