Recently, I have arranged the high frequency test questions on the front face and shared them with you to learn. If you have any questions, please correct me!
Note: 2021.5.21 has been updated to modify some errors in this article. Add a mind map, according to their own interview experience and the interview on the platform such as Niuker.com, the frequency of the interview questions will be roughly divided, can be targeted to review.
The following is a series of articles.
[1] “2021” high frequency front face test summary HTML article
[2] “2021” high-frequency front end of the CSS section
[3] 2021
[4] 2021
[5] “2021”
[6] “2021”
【7】 “2021” High-Frequency front end test questions summary
[8] “2021” high frequency front end test questions summary
[9] “2021” high frequency front end test question summary of computer network article
[10] “2021” high frequency front end test summary of browser principles
[11] the performance optimization of “2021” high frequency test paper summary
[12] “2021” high frequency front end of the handwritten code of the test summary
[13] “2021” high frequency front end test summary code output results
I. Component Foundation
1. React event mechanism
<div onClick={this.handleClick.bind(this)} > I < / div >Copy the code
Instead of binding the click event to the actual DOM of the div, React listens for all events in the document. When the event occurs and bubbles to the document, React wraps the event content and passes it to the actual handler. This approach not only reduces memory consumption, but also allows you to uniformly subscribe to and remove events when a component is on the hook for destruction.
In addition, the events bubbling onto the Document are not native browser events, but synthetic events implemented by React itself. So if you don’t want events to bubble you should call event.preventDefault() instead of event.stopProppagation().Events written on JSX are not bound to the corresponding real DOM. Instead, all events are bound to the DOM through the event proxydocument
On. This approach not only reduces memory consumption, but also allows for uniform subscription and removal of events when a component mounts and is destroyed.
In addition, the events that bubble onto the Document are not native browser events, but synthetic events implemented by React itself. So if we don’t want the event to bubble, call event.stopPropagation is invalid, call event.preventDefault instead.
The purpose of synthesizing events is as follows:
- Compositing events first smoothes out compatibility issues between browsers. In addition, it is a cross-browser native event wrapper that gives cross-browser development capabilities.
- For native browser events, the browser creates an event object for the listener. If you have a lot of event listeners, then you need to allocate a lot of event objects, resulting in a high memory allocation problem. For synthetic events, however, there is a pool of events to manage their creation and destruction. When the event needs to be used, the objects are reused from the pool. After the event callback, the properties on the event object are destroyed so that the event object can be reused next time.
How do React events differ from normal HTML events?
The difference between:
- For event names, native events are all lowercase, react events use a small hump;
- For event function handling syntax, native events are strings and React events are functions.
- The React event cannot return false to prevent the browser’s default behavior, but must be explicitly called
preventDefault()
To prevent the default behavior.
Synthesized events are an event object that React simulates all the capabilities of native DOM events. The benefits are as follows:
- Compatible with all browsers, better cross-platform;
- Keep events in one array to avoid frequent additions and deleutions (garbage collection).
- Convenient react unified management and transaction mechanism.
The execution sequence of events is that the native event is executed first, and the synthesized event is executed later. The synthesized event will bubble and bind to the document, so the mixing of the native event and the synthesized event should be avoided as far as possible. If the native event prevents the bubble, the synthesized event may not be executed, because the synthesized event will be executed only after the bubble is placed on the document.
3. How to do event proxies in the React component? How does it work?
React implements a SyntheticEvent layer (SyntheticEvent Layer) based on the Virtual DOM. The defined event handler receives an instance of a SyntheticEvent object, which is W3C compliant and has the same interface as native browser events. It supports the bubble mechanism, and all events are automatically bound to the outermost layer.
At the React level, there are two main things you do with composite events:
- Event delegate: React binds all events to the outermost layer of the structure, using a uniform event listener that maintains a map to all component internal event listeners and handlers.
- Automatic binding: In the React component, the context of each method points to an instance of that component, which automatically binds this to the current component.
4. What is the difference between React high-level components, Render props, hooks
These three are the main ways that React currently addresses code reuse:
- High Order Component (HOC) is an advanced technique used in React to reuse component logic. Instead of being part of the React API, HOC is a design pattern based on the React combinatorial features. Specifically, a higher-order component is a function that takes a component as an argument and returns a new component as a value.
- The render prop is a simple technique for sharing code between React components using a prop with a value of a function. More specifically, the render prop is a function that tells a component what to render.
- Typically, render props and high-level components render only one child node. It is easier to have hooks serve this usage scenario. Both modes are still useful (for example, a virtual scroll bar component might have a renderLTEM property, or a visible container component might have its own DOM structure). But in most cases, hooks are sufficient and can help reduce nesting.
(1) HOC official explanation
High Order Component (HOC) is an advanced technique used in React to reuse component logic. Instead of being part of the React API, HOC is a design pattern based on the React combinatorial features.
In short, HOC is a design pattern for a component, where it takes a component and additional parameters (if needed) and returns a new component. HOC is a pure function with no side effects.
// The definition of hoc
function withSubscription(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
data: selectData(DataSource, props)
};
}
// Some general logic processing
render() {
/ /... And render the wrapped components with the new data!
return <WrappedComponent data={this.state.data} {. this.props} / >; }};/ / use
const BlogPostWithSubscription = withSubscription(BlogPost,
(DataSource, props) = > DataSource.getBlogPost(props.id));
Copy the code
Advantages and disadvantages of HOC
- Advantage: Logic takes, does not affect the internal logic of the package.
- Disadvantages: Props passed by hoc to a wrapped component can easily have the same name as the wrapped component, thus overwriting it
(2) Props
“Render prop” is a simple technique for sharing code between React components using a prop with a function value
A component with a Render prop accepts a function that returns the React element, injecting Render’s rendering logic into the component. In this case, the name “render” can be any other valid identifier.
// The internal rendering logic of the DataProvider component is as follows
class DataProvider extends React.Components {
state = {
name: 'Tom'
}
render() {
return (
<div>
<p>The shared data component has its own internal rendering logic</p>
{ this.props.render(this.state) }
</div>); }}// Call mode
<DataProvider render={data= > (
<h1>Hello {data.name}</h1>)} / >Copy the code
The advantages and disadvantages of render props are also obvious
- Benefits: Data sharing, code reuse, passing state within the component as props to the caller, rendering logic to the caller.
- Disadvantages: No access to data outside of return statement, not elegant nesting
(3) Official explanation
Hooks are new in React 16.8. It lets you use state and other React features without having to write a class. By custom hooks, you can reuse the code logic.
// Customize a hook to get the subscription data
function useSubscription() {
const data = DataSource.getComments();
return [data];
}
//
function CommentList(props) {
const {data} = props;
const[subData] = useSubscription(); . }/ / use
<CommentList data='hello' />
Copy the code
As can be seen above, the hook solves the problem of covering the Prop of Hoc, while the method used solves the problem of nesting the inferno of render props. The advantages of hook are as follows
- Intuitive use;
- Solve the prop name problem of Hoc;
- [Fixed] Render props nesting hell for sharing data
- The issue of being able to use data outside of return.
It is important to note that hooks can only be used at the component level, not in branch statements.
Conclusion: Hoc, render props, and hook are all designed to solve the problem of code reuse, but both Hoc and render props have specific usage scenarios and obvious disadvantages. Hooks are a new API updated in Act 16.8 that makes component logic reusable more straightforward and addresses some of the drawbacks of Hoc and Render props.
5. Understanding of React-Fiber, what problems does it solve?
React V15 recursively compares the VirtualDOM tree to find the nodes that need to be changed, and updates them synchronously, all at once. During this process, React will occupy browser resources, which will result in no response to user-triggered events and frame drop, which will cause users to feel stuck.
In order to give the user the “illusion” that the application is fast, you can’t let one task hog resources for long. Rendering, layout, drawing, resource loading (such as HTML parsing), event response, and script execution of the browser can be considered as “processes” of the operating system. Some scheduling policies need to be used to properly allocate CPU resources to improve the user response rate of the browser and take into account the task execution efficiency.
So React, with the Fiber architecture, makes this execution interruptible. Ceding CPU execution “in time” has other benefits besides allowing the browser to respond to user interactions in a timely manner:
- DOM operation is performed in batches and delayed, avoiding the operation of a large number of DOM nodes at one time, which can provide better user experience.
- Give the browser a break and it will do compilation optimizations (JIT) and hot code optimizations, or reflow fixes.
Core idea: Fiber is also called coroutine or Fiber. Unlike threads, coroutines themselves have no concurrency or parallelism (they need to cooperate with threads), but are only a mechanism to control the flow of transfer. Give the CPU execution power so that it can perform other operations during this time. Rendering can be interrupted, and control can be handed back to the browser, giving way to higher-priority tasks, and rendering can be resumed when the browser is idle.
6. The difference between react.ponent and React.pureComponent
PureComponent represents a PureComponent that can be used to optimize the React program and reduce the number of times the render function is executed, thereby improving the performance of the component.
In React, when prop or state changes, you can prevent page updates by returning false in the shouldComponentUpdate lifecycle function, thus reducing unnecessary render execution. The React.PureComponent automatically executes shouldComponentUpdate.
However, shouldComponentUpdate() in the pureComponent does a shallow comparison, which means that if data is referenced to a datatype, it will only be compared to the same address, not to the same address. Shallow comparisons ignore property and/or state mutations, which means that the data reference pointer does not change, and render does not execute when the data changes. If you need to re-render then you need to re-open the space reference data. PureComponent is typically used for purely presentation components.
Advantage of using pureComponent: The render function does not fire when the component is updated if neither the props nor the state of the component has changed. The process of generating and comparing virtual DOM can be eliminated to improve performance. That’s because React automatically makes a light comparison.
7. What is the difference and connection between Component, Element and Instance?
- Chemical element:One of the elements
element
Is a plain Object that describes the status of a DOM node or other componentcomponent
What you want it to look like on the screen. The elementelement
It can be in its propertiesprops
Contains other elements in the tree. Create a React elementelement
The cost is very low. The elementelement
Once created, it is immutable. - Components:A component
component
This can be declared in a number of ways. It could be with onerender()
The class of a method can be simply defined as a function. In both cases, it takes the propertyprops
As input, a returned tree of elements is used as output. - Example:An instance
instance
Is the component class you are writingcomponent class
The keyword is used in thethis
To which the component is pointing. It is useful for storing local state and responding to life cycle events.
Functional Components have no instance at all. Class Component has instance, but you never need to create an instance of the component directly, because React does that for us.
What’s the difference between a react. createClass and an extends Component?
The bai difference between React.createClass and extends Component is:
(1) Grammatical differences
- CreateClass is essentially a factory function that extends in a way that more closely resembles the class writing of the latest ES6 specification. The syntax differences between the two approaches are mainly in the definition of methods and the declaration of static properties.
- The createClass method definition is separated by commas, because creatClass is essentially a function that is passed an Object. When defining methods in the class way, remember not to use commas to separate them. This is the ES6 class syntax.
(2) propType and getDefaultProps
- React.createclass: Sets and gets props via the proTypes object and the getDefaultProps() method.
- React.ponent: By setting two properties, propTypes and defaultProps
(3) The difference between states
- React.createclass: Returns an object containing the initial value via the getInitialState() method
- React.ponent: Set the initial state via constructor
(4)
- React. CreateClass: this is bound correctly
- React.ponent: With ES6, this is slightly different. Properties are not automatically bound to React class instances.
(5) Mixins
- CreateClass: With React. CreateClass, you can add a property called mixins when creating components and assign mixins an array of classes that can be mixed.
- If you use the ES6 approach to create components, then
React mixins
The feature will not be used.
9. What is the React high-level component? What is the difference between the React high-level component and the normal component
Official explanation:
High Order Component (HOC) is an advanced technique used in React to reuse component logic. Instead of being part of the React API, HOC is a design pattern based on the React combinatorial features.
A high-order component (HOC) is just a function that takes a component as a parameter and returns a new component. It is just a design pattern for a component that is necessarily generated by the combinatorial nature of React itself. We call them pure components because they can accept any dynamically supplied child component, but they do not modify or copy any behavior in their input component.
// The definition of hoc
function withSubscription(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
data: selectData(DataSource, props)
};
}
// Some general logic processing
render() {
/ /... And render the wrapped components with the new data!
return <WrappedComponent data={this.state.data} {. this.props} / >; }};/ / use
const BlogPostWithSubscription = withSubscription(BlogPost,
(DataSource, props) = > DataSource.getBlogPost(props.id));
Copy the code
1) Advantages and disadvantages of HOC
- Advantage: Logic takes, does not affect the internal logic of the package.
- Disadvantages: Props passed by hoc to a wrapped component can easily have the same name as the wrapped component, thus overwriting it
2) Application scenario
- Code reuse, logic abstraction
- Rendering hijacked
- State abstractions and changes
- Props to change
3) Specific application examples
- Permission control: The conditional rendering feature of high-level components can be used to control the permission of the page. The permission control is generally divided into two dimensions: page level and page element level
// HOC.js
function withAdminAuth(WrappedComponent) {
return class extends React.Component {
state = {
isAdmin: false,}async UNSAFE_componentWillMount() {
const currentRole = await getCurrentUserRole();
this.setState({
isAdmin: currentRole === 'Admin'}); }render() {
if (this.state.isAdmin) {
return <WrappedComponent {. this.props} / >;
} else {
return (<div>You do not have permission to view this page, please contact your administrator!</div>); }}}; }// pages/page-a.js
class PageA extends React.Component {
constructor(props) {
super(props);
// something here...
}
UNSAFE_componentWillMount() {
// fetching data
}
render() {
// render page with data}}export default withAdminAuth(PageA);
// pages/page-b.js
class PageB extends React.Component {
constructor(props) {
super(props);
// something here...
}
UNSAFE_componentWillMount() {
// fetching data
}
render() {
// render page with data}}export default withAdminAuth(PageB);
Copy the code
- Component rendering performance tracking: It is convenient to record the rendering time of a component by capturing the life cycle of the child component with the parent component child component life cycle rule
class Home extends React.Component {
render() {
return (<h1>Hello World.</h1>); }}function withTiming(WrappedComponent) {
return class extends WrappedComponent {
constructor(props) {
super(props);
this.start = 0;
this.end = 0;
}
UNSAFE_componentWillMount() {
super.componentWillMount && super.componentWillMount();
this.start = Date.now();
}
componentDidMount() {
super.componentDidMount && super.componentDidMount();
this.end = Date.now();
console.log(`${WrappedComponent.name}Component rendering time isThe ${this.end - this.start} ms`);
}
render() {
return super.render(); }}; }export default withTiming(Home);
Copy the code
Note: withTiming is a high-level component implemented using reverse inheritance to calculate the render time of the wrapped component (in this case, the Home component).
- Page reuse
const withFetching = fetching= > WrappedComponent= > {
return class extends React.Component {
state = {
data: [],}async UNSAFE_componentWillMount() {
const data = await fetching();
this.setState({
data,
});
}
render() {
return <WrappedComponent data={this.state.data} {. this.props} / >; }}}// pages/page-a.js
export default withFetching(fetching('science-fiction'))(MovieList);
// pages/page-b.js
export default withFetching(fetching('action'))(MovieList);
// pages/page-other.js
export default withFetching(fetching('some-other-type'))(MovieList);
Copy the code
10. Understanding of componentWillReceiveProps
This method is executed when props change, but not when render is initialized. Inside this callback function, you can update the state of your component by calling this.setstate () based on the property change. The old properties can still be fetched by calling this.props. Additional render calls are not triggered.
Use benefit: During this lifecycle, you can update the child component’s own state by fetching new props before its render function executes. May perform data request here, and the need to pass parameters from componentWillReceiveProps (nextProps). Instead of putting all requests in the parent component. The request is then made only when the component is rendered, reducing the request burden.
ComponentWillReceiveProps when initializing render will not perform, it will be accepted in the Component to the new state (Props) is triggered, commonly used in the parent Component state update subcomponents of rendering.
11. Which methods trigger React to rerender? What does rerender do?
(1) Which methods trigger react rerender?
- The setState () method is called
SetState is the most commonly used command in React. Normally, executing setState triggers render. But one thing to note is that setState does not necessarily rerender. Render does not fire when setState is passed to NULL.
class App extends React.Component {
state = {
a: 1
};
render() {
console.log("render");
return (
<React.Fragement>
<p>{this.state.a}</p>
<button
onClick={()= >{ this.setState({ a: 1 }); // There is no change in a value}} > Click me</button>
<button onClick={()= > this.setState(null)}>setState null</button>
<Child />
</React.Fragement>); }}Copy the code
- The parent component is rerendered
As long as the parent component rerenders, the child component will rerender, triggering render, even if the props passed to it have not changed
(2) What do I do when I rerender?
- The new VNode is compared to the new VNode, which is called the Diff algorithm.
- Carry out a depth-first traversal of the old and new trees, so that each node will have a mark. During the depth traversal, each node will be compared with the new node tree, and if there is a difference, it will be put into an object
- Traversing the difference objects, updating the VNode based on the type of the difference, and based on the coping rules
React’s basic mindset for handling render is to rerender the entire application every time there is a change. Before Virtual DOM, the easiest way to do this was to call innerHTML directly. The great thing about the Virtual DOM is not that it is faster than direct DOM manipulation, but that it updates the DOM with minimal cost, no matter how the data changes. React compares the virtual DOM tree returned by the Render function to the old one to determine if and how the DOM should be updated. When the DOM tree is very large, it can be quite performance intensive to walk through the two trees and make various comparisons, especially if a small change in the top-level setState is the default to walk through the whole tree. Although React uses the highly optimized Diff algorithm, this process still takes a performance toll.
12. How does React determine when to rerender components?
A component’s state can be changed by using props or by using the setState method directly. The component gets the new state, and React decides if the component should be rerendered. React rerenders a component whenever its state changes. This is because the React shouldComponentUpdate method returns true by default, which causes it to be rerendered with each update.
When React is about to render a component, it executes the shouldComponentUpdate method to see if it returns true (the component should be updated, i.e. re-rendered). So we need to override the shouldComponentUpdate method and have it return true or false depending on the situation to tell React when to rerender and when to skip rerender.
13. What are the different ways to declare the React component?
React declares components in three ways:
- It’s defined functionally
Stateless component
- ES5 native mode
React.createClass
Defined components - In the form of ES6
extends React.Component
Defined components
(1) Stateless function component this is to create a pure presentation component that is only responsible for presenting functions according to the props passed in. Action components that do not involve the state state will not be instantiated. Overall rendering performance is improved
(2) ES5 native react.createclass // RFC React.createclass will self-bind function methods, resulting in unnecessary performance overhead and increasing the likelihood of code obsolescing.
(3) React.createclass // RCC is currently a highly recommended way to create stateful components, eventually replacing the React.createclass form; Compared to React. CreateClass, code reuse is better.
Stateless components vs. stateless components: In contrast to stateless components, React.createClass and react.ponent create stateless components that are instantiated and have access to the component’s lifecycle methods.
React.createClass react. createClass
① This function is self-binding
- CreateClass creates a component whose member function this is automatically bound to the React function. This in the function is set correctly.
- React.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.component.
(2) the component attribute type propTypes and its defaultProps attribute defaultProps are configured differently
- CreateClass When a component is created, the component props attribute types and the component default attributes are configured as component instance properties. DefaultProps uses getDefaultProps to get the default component properties
- When react.componentconfigures these two corresponding information at component creation time, they are configured as properties of the component class, not as properties of the component instance, which is called static properties of the class.
③ The initial state configurations of components are different
- CreateClass creates a component whose state is configured using the getInitialState method.
- React.componentcreates a component whose state is declared in Constructor as if it were initializing component properties.
14. Understanding and usage scenarios of stateful and stateless components
(1) Stateful components
Features:
- Is a kind of component
- Have inherited
- You can use this
- You can use the React lifecycle
- It is easy to trigger the lifecycle hook function frequently, which affects the performance
- The stateful component uses state internally to maintain its own state changes. The stateful component renders props and its own state as incoming from an external component.
Usage scenario:
- Need to use the state.
- – you need to use state to operate components (stateless components can be implemented as well as the new react hooks)
Bottom line: Class components can maintain their own state variables, that is, the state of the component. Class components also have different lifecycle methods that allow developers to have more control over a component at different stages (mount, update, uninstall). Class components can act as either stateless or stateful components. A class component is also called a stateless component when it does not need to manage its own state.
(2) Stateless component features:
- Does not depend on its state
- It can be a class component or a function component.
- You can avoid using the this keyword entirely. (Event binding is not required because the arrow function is used)
- Higher performance. When lifecycle hooks are not needed, stateless function components should be used first
- A component that does not maintain state internally and only renders props that are passed in from an external component. When the props change, the component rerenders.
Usage scenario:
- Components do not need to manage state, pure display
Advantages:
- Simplify the code and focus on Render
- Components do not need to be instantiated, have no lifecycle, and improve performance. The output (rendering) depends only on the input (properties), with no side effects
- Decoupling of views and data
Disadvantages:
- Unable to use REF
- Non-lifecycle approach
- There is no control over the rerendering of the component because the shouldComponentUpdate method cannot be used and the component will be rerendered when it receives a new property
Summary: For components with internal state that are independent of external states, consider using state components so that the state tree is not too complex and easy to understand and manage. When a component does not need to manage its own state, that is, a stateless component, it should be designed as a function component first. Such as custom , components.
15. Understand Fragment in React, what are its usage scenarios?
In React, components can only return elements with one root element. To avoid adding extra DOM nodes, we can wrap all the elements using the Fragment tag, which does not render any elements. React official Fragment explanation:
A common pattern in React is for a component to return multiple elements. Fragments allow you to group sublists without adding additional nodes to the DOM.
import React, { Component, Fragment } from 'react'
// General form
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
// It can also be written in the following form
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
Copy the code
How to React to a component’s DOM element?
You can use ref to get an instance of a child node, and then directly get the child node instance using some specific properties of the current class component instance. There are three ways to implement the REF:
- String format: string format, which was most used before React16, for example:
<p ref="info">span</p>
- Function format: ref corresponds to a method that takes one parameter, the corresponding node instance, such as:
<p ref={ele => this.info = ele}></p>
- CreateRef method: An API provided in React 16, implemented using react.createref ()
17. Can I access refs from Render in React? Why is that?
<>
<span id="name" ref={this.spanRef}>{this.state.title}</span>
<span>{ this.spanRef.current ? 'Value' : 'No value'}</span>
</>
Copy the code
No, the DOM has not been generated in the Render phase. DOM acquisition is required in the pre-commit phase and the COMMIT phase:
18. Understanding of The React Portals, how to use them, and in what scenarios
The React official definition of Portals:
Portal provides an excellent solution for rendering child nodes to DOM nodes that exist outside the parent component
Portals are the official solution provided by React 16, allowing components to be mounted anywhere in the DOM tree outside of the parent component hierarchy. We render a component, but the DOM structure of the component is not in the component.
“Portals” syntax is as follows:
ReactDOM.createPortal(child, container);
Copy the code
- The first argument child is a renderable React child, such as an element, string, or fragment.
- The second parameter, Container, is a DOM element.
Normally, the element returned by a component’s render function is mounted on its parent component:
import DemoComponent from './DemoComponent';
render() {
// The DemoComponent element will be mounted on the parent div element
return (
<div id="parent">
<DemoComponent />
</div>
);
}
Copy the code
However, some elements need to be mounted at a higher level. The most typical application scenario: When the parent component has the overflow: Hidden or Z-index style setting, and the component is likely to be obscured by other elements, consider using Portal to mount the component away from the parent component. For example: dialog box, modal window.
import DemoComponent from './DemoComponent';
render() {
// The DemoComponent element will be mounted on the parent div element
return (
<div id="parent">
<DemoComponent />
</div>
);
}
Copy the code
19. How to avoid unnecessary render in React?
React, based on the perfect combination of virtual DOM and efficient Diff algorithm, realizes the smallest granularity of DOM update. For the most part, React renders the DOM efficiently enough for everyday business. However, in some complex business scenarios, performance issues still plague us. At this point, some measures need to be taken to improve performance. One important direction is to avoid unnecessary Render. Here are some optimization points:
- ShouldComponentUpdate and PureComponent
In React class components, shouldComponentUpdate or PureComponent can be used to reduce the number of parent component updates that trigger the child component render. ShouldComponentUpdate determines whether the component should be rerendered. If you do not want the component to be rerendered, return false.
- Utilize higher-order components
In function components, there is no shouldComponentUpdate lifecycle, can use higher-order components, a similar PureComponet encapsulated functionality
- Use the React. Memo
React. Memo is a new API for Caching component renderings in React 16.6 to avoid unnecessary updates. It is also a higher-order component, similar to PureComponent, but it can only be used for function components.
20. Understanding of React-Intl and how it works?
React-intl is part of FormatJS, Yahoo’s open source language internationalization project, which provides components and apis to bind to ReactJS.
React-intl provides two ways to use it. One is to refer to the React component, and the other is to call the API directly. It is recommended to use the former in the React project. It provides a range of React components, including number formatting, string formatting, date formatting, and more.
In React-Intl, you can configure different language packs, and it works by switching between them as needed.
21. Understanding React context
In React, data is generally passed using props to maintain a one-way data flow. This makes the relationship between components simple and predictable, but a single data flow is not appropriate in some scenarios. There’s no problem with simply passing a parent to a child component, but if you have a lot of dependencies between components, props need to be passed one at a time, and obviously that’s too tedious to do.
Context provides a way to share such values between components without having to explicitly pass props through the component tree.
You can think of a context as a shared store within a particular component tree for data transfer. In short, when you don’t want to pass props or states across the component tree, you can use Context to pass data across the component hierarchy.
During the execution of a JS code block, a corresponding scope chain is created. This scope chain records the active objects, including variables and functions, that can be accessed during the execution of the JS code block at runtime. The JS program accesses variables and functions inside or outside the code block through the scope chain.
Using the JS scope chain analogy, the React component provides a Context object that is actually a scope for children to access, and the properties of the Context object can be thought of as an active object on the scope. Since a component’s Context is composed of the Context object returned by all components on the parent node chain via getChildContext (), a component’s Context is a property that can access the Context provided by all node components on the parent node chain.
22. Why does React not recommend using Context first?
- Context is still experimental and may change a lot in later releases, which is already happening, so it is not recommended to use Context in your app to avoid a major impact and trouble in future upgrades.
- Although it is not recommended to use a context in an app, for a unique component, the scope of impact is smaller than that of an app. If you can achieve high cohesion without breaking the dependencies between the component tree, you can consider using a context
- For data communication between components or state management, use props or state effectively, and then consider using mature third-party libraries. When none of the above is the best solution, consider context.
- Context updates need to be triggered by setState(), but this is not very reliable. Context supports cross-component access, but if the intermediate sub-component does not affect the update through some method, For example, shouldComponentUpdate() returns false, so there is no guarantee that Context updates can be made using sub-components of the Context. Therefore, Context reliability needs to be concerned
23. What are controlled and uncontrolled components in React?
(1) When the controlled component uses the form to collect user input, such as
Controlled components update state process:
- Default values for the form can be set in the initial state
- The onChange event handler is called whenever the value of the form changes
- The event handler gets the changed state from the event object e and updates the state of the component
- Once the state is updated through the setState method, a re-rendering of the view is triggered, completing the update of the form component
Controlled component defects: the values of form elements are run by the React components, when there are multiple input box, or multiple this component, if you want to get at the same time to the entire value must be each to write the event handler, it will make the code be bloated, so in order to solve this kind of situation, the uncontrolled components.
A form component is called an uncontrolled component if it does not have value props (checked props for radio and check buttons). In an uncontrolled component, you can use a ref to get the form value from the DOM. Instead of writing an event handler for each status update.
React’s official explanation:
To write an uncontrolled component, instead of writing a data handler for each state update, you can use the REF to fetch form data from the DOM node. Because uncontrolled components store real data in DOM nodes, it is sometimes easier to integrate React and non-React code together when using uncontrolled components. If you don’t mind the beauty of your code and want to write it quickly, using uncontrolled components can often reduce your code volume. Otherwise, you should use controlled components.
For example, the following code receives a single property in an uncontrolled component:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={(input)= > this.input = input} />
</label>
<input type="submit" value="Submit" />
</form>); }}Copy the code
Summary: The DOM of all input classes in the page is called uncontrolled component if it is used and retrieved. The input value is maintained in state through setState, and retrieved from state when needed. The data here is controlled by state, which is called controlled component.
24. What is the role of refs in React? What are the application scenarios?
Refs provides a way to access React elements or DOM nodes created in render methods. Refs should be used with caution. Refs is suitable for the following scenarios:
- Handles focus, text selection, or media control
- Trigger the necessary animations
- Integrate third-party DOM libraries
Refs are created using the React.createref () method, which is attached to the React element via the ref attribute. To use Refs throughout the component, assign ref to the example property in the constructor:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
render() {
return <div ref={this.myRef} />}}Copy the code
Since the function component has no instance, you cannot use the ref directly on the function component:
function MyFunctionalComponent() {
return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
// This will not work!
return (
<MyFunctionalComponent ref={this.textInput} />); }}Copy the code
However, Refs can be used inside function components with closed help:
function CustomTextInput(props) {
// textInput must be declared so that the ref callback can reference it
let textInput = null;
function handleClick() {
textInput.focus();
}
return (
<div>
<input
type="text"
ref={(input)= >{ textInput = input; }} / ><input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
Copy the code
Note:
- Refs should not be used excessively
ref
Depends on the type of the node:- when
ref
When the attribute is used on a normal HTML element,React.createRef()
Receives the underlying DOM element as hiscurrent
Property to createref
. - when
ref
Property is used by a custom class component,ref
Object will receive the mounted instance of the component as its owncurrent
.
- when
- When a parent component needs to access a child component
ref
Pass Refs or callback Refs can be used.
26. What does the React constructor do? Is it necessary?
Constructors are used for two purposes:
- Initialize the local state by assigning an object to this.state
- Bind the event handler method to the instance
If you need to set the initial value of state or bind an event in the React class, you need to add the constructor.
class LikeButton extends React.Component {
constructor() {
super(a);this.state = {
liked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({liked:!this.state.liked});
}
render() {
const text = this.state.liked ? 'liked' : 'haven\'t liked';
return (
<div onClick={this.handleClick}>
You {text} this. Click to toggle.
</div>
);
}
}
ReactDOM.render(
<LikeButton />.document.getElementById('example'));Copy the code
Constructor to create a new this object of the parent class; Subclasses must call the super method within the constructor method; Otherwise, the new instance will report an error; Because a subclass does not have its own this object, it inherits from its parent class’s this object and then processes it. If you don’t call the super method; Subclasses don’t get this object.
Note:
- Constructor () must be accompanied by super(). If you want to use this.props inside constructor, pass props otherwise
- JavaScript bind returns a new function each time. For performance reasons, try to bind events within Constructor
What is the React. ForwardRef? What does it do?
ForwardRef creates a React component that can forward its accepted REF properties to another component in its component tree. This technique is not common, but is particularly useful in two scenarios:
- Forward refs to the DOM component
- Forward refs in high-level components
28. What are the similarities and differences between class components and function components?
Similarities: Components are the smallest code snippets that React can reuse, and they return React elements to render on the page. Because component is the smallest coding unit of React, both function component and class component are used in the same way and the final rendering effect.
We can even rewrite a class component into a function component, or a function component into a class component (although this refactoring is not recommended). From a consumer perspective, it is difficult to distinguish between the two in terms of experience, and in modern browsers, the performance of closures and classes differs significantly only in extreme scenarios. Therefore, it can be considered that the two components are exactly the same.
Difference:
- There is a huge difference in the mental model of development. Class component is based on object-oriented programming, it is the main inheritance, life cycle and other core concepts; And the function component kernel is functional programming, the main is immutable, no side effects, transparent reference and other characteristics.
- Previously, in the usage scenario, if there are components that need to use the lifecycle, then the main push class component; As a design pattern, if you need to use inheritance, then push the class component. But now with the introduction of React Hooks, the lifecycle concept has faded out and function components can completely replace class components. Second, inheritance is not the best design pattern for components. The official concept of “combination is better than inheritance” is preferred, so the advantage of class components in this respect is fading.
- In terms of performance optimization, class components mainly rely on shouldComponentUpdate to block rendering to improve performance, while function components rely on React. Memo to cache rendering results to improve performance.
- In terms of getting started, class components are easier to get started with, and in terms of the future, with the React Hooks, function components are the future of the community.
- Class components in future time slicing and concurrent patterns are not easy to optimize due to the complexity of the life cycle. The function components themselves are lightweight, simple, and provide more fine-grained logic organization and reuse based on Hooks, making them more adaptable to future developments in React.
2. Data management
1. React setState call principle
The specific execution process is as follows (source code parsing) :
- The first call is
setState
Entry function, the entry function here is to act as a dispenser, according to the different input parameters, it will be distributed to different function functions;
ReactComponent.prototype.setState = function (partialState, callback) {
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState'); }};Copy the code
enqueueSetState
Method will be newstate
Put it in the component’s status queue and callenqueueUpdate
To handle the instance object to be updated;
enqueueSetState: function (publicInstance, partialState) {
// Get the corresponding component instance according to this
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
// This queue corresponds to an array of states for each component instance
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
// enqueueUpdate is used to process the current component instance
enqueueUpdate(internalInstance);
}
Copy the code
- in
enqueueUpdate
Method leads to a key object —batchingStrategy
, which the object hasisBatchingUpdates
Attributes directly determine whether to go through the update process or wait in a queue. If it’s time to execute, callbatchedUpdates
Method to initiate the update process directly. From this we can infer that,batchingStrategy
Perhaps it is the object inside React that is used to control batch updates.
function enqueueUpdate(component) {
ensureInjected();
// isBatchingUpdates specifies whether or not the component is being batch created/updated
if(! batchingStrategy.isBatchingUpdates) {// Update components immediately if they are not currently in the batch create/update phase
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
// Otherwise, put the component in the dirtyComponents queue and let it "wait".
dirtyComponents.push(component);
if (component._updateBatchNumber == null) {
component._updateBatchNumber = updateBatchNumber + 1; }}Copy the code
Note: The batchingStrategy object can be understood as “lock manager”. “Lock” refers to the React globally-unique isBatchingUpdates variable, whose initial value is false, which means “no batch updates are currently being performed”. When React calls batchedUpdate to perform an update action, it will first “lock” (set to true), indicating that it is “currently in the batch update process”. When the lock is “locked”, any component that needs to be updated can only be temporarily queued in dirtyComponents for the next batch update, rather than “jumping the queue” at will. The idea of “task locking” embodied here is the cornerstone of React’s ability to implement ordered batching in the face of a large number of states.
2. What happens after the React setState call? Is it synchronous or asynchronous?
(1) what happens when you setState in React
After the setState function is called in the code, React merges the passed parameter objects with the component’s current state, and then triggers the Reconciliation process. After the concatenation process, React builds the React element tree based on the new state in a relatively efficient way and starts to rerender the entire UI.
After React gets the element tree, React automatically calculates the node differences between the new tree and the old tree, and then minimizes the rerendering of the interface based on the differences. In the differential calculation algorithm, React is able to know with relative accuracy which positions have changed and how, which ensures that it is updated on demand rather than re-rendering everything.
If you setState frequently in a short period of time. React pushes state changes onto the stack and updates state and views in batches when appropriate to improve performance.
(2) Whether setState is synchronous or asynchronous
If all setstates are synchronized, this means that every time a setState is executed (possibly multiple setstates in a synchronized code), vnode diff + DOM changes are redone, which is very bad for performance. If asynchronous, you can combine multiple setstates in a synchronous code into a single component update. So by default it is asynchronous, but in some cases it is synchronous.
Rather than being purely synchronous/asynchronous, setState behaves differently depending on the scenario in which it is called. In the source code, we use isBatchingUpdates to determine whether setState is stored in the state queue or updated directly. If true, we perform asynchronous operations, and if false, we update directly.
- Asynchronous: True where React has control, such as in React life cycle events and composite events.
- Sync: Where React does not control events, such as native events, such as addEventListener, setTimeout, setInterval, etc., you can only synchronize updates.
In general, asynchronous design is done to optimize performance and reduce render times:
setState
Designed to be asynchronous, it can significantly improve performance. If every time I callsetState
All of them are updated once, so that meansrender
Functions are called frequently and the interface is rerendered, which is inefficient; The best way to do this is to get multiple updates and batch them.- If the synchronization is updated
state
But it hasn’t been implemented yetrender
Function, sostate
andprops
The synchronization cannot be maintained.state
andprops
Failure to maintain consistency creates a lot of problems in development;
3. What is the batch update process of setState in React?
When you call setState, the component’s state does not change immediately. SetState simply puts the state to be changed in a queue. React optimizes the actual execution time and for performance reasons, Will combine state changes from multiple setStates in React event handlers into a single state change. The final update produces only one re-rendering of the component and its children, which is critical for performance gains in large applications.
this.setState({
count: this.state.count + 1===> Join the queue, [count+1]});this.setState({
count: this.state.count + 1===> Join the queue, [count+1Task, count+1]}); ↓ Merge state, [count+1] ↓ Execute count+1The task ofCopy the code
Note that the “save” action does not stop as long as the synchronization code is executing. (Note: the reason why +1 only works once is because merging multiple setstates in the same method does not simply add up updates. For example, React will only reserve the last update for the same property.
4. Do you use getDefaultProps in React? What does it do?
Set the default value for the property by implementing the component’s getDefaultProps:
var ShowTitle = React.createClass({
getDefaultProps:function(){
return{
title : "React"}},render : function(){
return <h1>{this.props.title}</h1>}});Copy the code
5. What does the second setState argument in React do?
The second argument to setState is an optional callback function. This callback function is executed after the component is rerendered. Equivalent to executing during the componentDidUpdate lifecycle. It is usually recommended to use componentDidUpdate instead. In this callback function you can get the updated value of state:
this.setState({
key1: newState1,
key2: newState2,
...
}, callback) // The second argument is the callback function after the state update is complete
Copy the code
6. What is the difference between setState and replaceState in React?
(1) setState() setState() is used to set the state object.
setState(object nextState[, function callback])
Copy the code
- NextState, the new state to be set, which will be merged with the current state
- Callback, optional parameter, callback function. This function is called after setState has been set successfully and the component has been rerendered.
Merge nextState with the current state, and re-render the component. SetState is the primary method for triggering UI updates in React event handlers and request callbacks.
(2) replaceState() the replaceState() method is similar to setState(), but only keeps the state in the nextState. All states that are not in the nextState are removed. The syntax is as follows:
replaceState(object nextState[, function callback])
Copy the code
- NextState, the new state to be set, which replaces the current state.
- Callback, optional parameter, callback function. This function is called after replaceState has been set successfully and the component has been rerendered.
Conclusion: setState is modify one part of the state, is equivalent to the Object. The assign, just cover, will not reduce its original state. ReplaceState completely replaces the original state, which is equivalent to assignment, replacing the original state with another object. If the new state property is reduced, then there is no state in state.
7. What is the difference between this.state and setState in the React component?
This. state is usually used to initialize state, and this.setState is used to modify the value of state. If we use this.state after we have initialized state, the previous state value will be overwritten. If we use this.setState, we will only replace the corresponding state value. So, if you want to change the value of state, you need to use setState. You can’t change state directly, and the page won’t be updated.
8. How is state injected into components? What is the process from reducer to components
Inject state into a component using connect and mapStateToProps:
import { connect } from 'react-redux'
import { setVisibilityFilter } from '@/reducers/Todo/actions'
import Link from '@/containers/Todo/components/Link'
const mapStateToProps = (state, ownProps) = > ({
active: ownProps.filter === state.visibilityFilter
})
const mapDispatchToProps = (dispatch, ownProps) = > ({
setFilter: () = > {
dispatch(setVisibilityFilter(ownProps.filter))
}
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Link)
Copy the code
In the above code, active is the state injected into the Link component. MapStateToProps (state, ownProps) contains two parameters, which are:
- State-store Managed global state object in which all component state data is stored.
- OwnProps Specifies the parameters passed in by the props component.
The reducer goes through the following processes to the component:
- The Reducer processes the Action object, updates the component state, and returns the new state value to the Store.
- To upgrade a Component using connect (mapStateToProps, mapDispatchToProps) (Component), fetch the status value from the store and pass it to the Component as the props parameter.
High – order component implementation source:
import React from 'react'
import PropTypes from 'prop-types'
// Advanced component contect
export const connect = (mapStateToProps, mapDispatchToProps) = > (WrappedComponent) = > {
class Connect extends React.Component {
// Get the store by calling context
static contextTypes = {
store: PropTypes.object
}
constructor() {
super(a)this.state = {
allProps: {}}}// The first step is to initialize all components
componentWillMount() {
const store = this.context.store
this._updateProps()
store.subscribe(() = > this._updateProps()); // Add _updateProps() to the list of listener events in the store
}
// Update props to update the component to the latest state (similar to setState).
_updateProps() {
const store = this.context.store;
let stateProps = mapStateToProps ?
mapStateToProps(store.getState(), this.props) : {} // Prevent mapStateToProps from being passed in
let dispatchProps = mapDispatchToProps ?
mapDispatchToProps(store.dispatch, this.props) : {
dispatch: store.dispatch
} // Prevent mapDispatchToProps from being passed in
this.setState({
allProps: {... stateProps, ... dispatchProps, ... this.props } }) }render() {
return <WrappedComponent {. this.state.allProps} / >}}return Connect
}
Copy the code
9. What’s the difference between state and props for the React component?
(1) the props
Props is a parameter passed from an external component. It is used to pass data from the parent component to the child component. It is readable and invariable.
(2) the state
The main function of state is to save, control, and modify the state of the component. It can only be initialized in constructor. It is a private property of the component and cannot be accessed or modified externally.
(3) Differences
- Props are passed to the component (similar to function parameters), while state is managed within the component itself (similar to a variable declared within a function).
- Props are immutable, and all React components must protect their props as if they were pure functions.
- State is created in a component and is typically initialized in Constructor. State is mutable, modifiable, and updated asynchronously with each setState.
10. Why is props in React read-only?
This.props is an interface for communication between components. In principle, it can only flow from parent to child components. React has a strong functional programming mentality.
When we talk about functional programming, we should mention one concept: pure functions. It has several features:
- Given the same input, the same output is always returned.
- There are no side effects.
- Independent of external state.
This. props is a reference to the idea of pure functions. The immutability of props guarantees the same input, the same page display, and no side effects
11. What are some ways to update a component when its props change in React?
In a component of the incoming props update to render the component commonly used method is in the heart of the componentWillReceiveProps new props to update to the components in the state of state (this state is Derived (Derived state)), so as to realize to rendering. React 16.3 also introduced a new hook function, getDerivedStateFromProps, to specifically implement this requirement.
(1) componentWillReceiveProps (obsolete)
In the react componentWillReceiveProps (nextProps) life cycle, can be in front of the child components render function to execute, through this. Props to get the old attribute, through nextProps for new props, Update the child component’s own state by comparing the two props to see if they are the same.
This advantage is that can put data requests to perform here, the parameters of the need to transfer from componentWillReceiveProps (nextProps). Instead of putting all requests in the parent component. The request is then made only when the component is rendered, reducing the request burden.
(2) getDerivedStateFromProps
The life cycle function is to replace componentWillReceiveProps exist, so the need to use componentWillReceiveProps, can consider to use getDerivedStateFromProps for replacement.
The arguments are different, and getDerivedStateFromProps is a static function. This means that this function cannot access the class properties, and direct access to the properties is not recommended. Instead, we should look at the nextProps and prevState provided by the arguments, and map to state based on the newly passed props.
Note that if the contents of the props are passed do not need to affect your state, then you need to return null. This is required, so try to write it at the end of the function:
static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// Update the state when the passed type changes
if(type ! == prevState.type) {return {
type,
};
}
// Otherwise, do nothing about state
return null;
}
Copy the code
12. How to check props in React? What was the purpose of verifying Props?
React provided us with PropTypes for verification purposes. We will issue a warning message on the console when the data we passed to the Props is invalid (the data type we passed to the Props does not match the data type we validated). It avoids the problems that arise as applications become more complex. It also makes the program easier to read.
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
Copy the code
Of course, if the project assembly uses TypeScript, you can use TypeScript to define interfaces for props instead of PropTypes.
Iii. Life cycle
1. What is the React lifecycle?
React typically divides the component life cycle into three phases:
- Mount, the first time a component is rendered in the DOM tree;
- Update, when the component state changes, the rendering process is updated again.
- Unmount, the process of removing a component from the DOM tree
1) Component mounting phase
During the mount phase, the component is created, the component instance is inserted into the DOM, and the component is rendered for the first time. This only happens once, and the following methods are called in turn:
- constructor
- getDerivedStateFromProps
- render
- componentDidMount
(1) constructor
The component’s constructor is the first to be executed. If it is not explicitly defined, there is a default constructor. But if the constructor is explicitly defined, we must execute super(props) in the constructor, otherwise we cannot get this in the constructor.
If state is not initialized or method binding is not performed, there is no need to implement Constructor for the React component.
Constructor usually does only two things:
- Initialize the state of the component
- Bind this to the event handling method
constructor(props) {
super(props);
// Do not call setState in the constructor. You can set the initial value of state directly
this.state = { counter: 0 }
this.handleClick = this.handleClick.bind(this)}Copy the code
(2) getDerivedStateFromProps
static getDerivedStateFromProps(props, state)
Copy the code
This is a static method, so you can’t use this in this function. It takes props and state, which refer to the new parameter received and the state object of the current component. This function returns an object to update the current state object, or null if no update is required.
This function is called at load time, when a new props is received, or when setState and forceUpdate are called. If you want to change state when you receive a new property, you can use it.
// When props. Counter changes, assign the value to state
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
counter: 0}}static getDerivedStateFromProps(props, state) {
if(props.counter ! == state.counter) {return {
counter: props.counter
}
}
return null
}
handleClick = () = > {
this.setState({
counter: this.state.counter + 1})}render() {
return (
<div>
<h1 onClick={this.handleClick}>Hello, world! {this.state.counter}</h1>
</div>)}}Copy the code
Now you can explicitly pass counter, but there is a problem. If you want to increment state.counter by clicking on it, you’ll find that the value doesn’t change at all. It stays the same value as the props passed in. This is because in React 16.4^, setState and forceUpdate also trigger this lifecycle, so when the component’s internal state changes, the method will be re-invoked, assigning the state value to the props value. Therefore, you need to add an extra field to record the props value, which will solve the above problem. The details are as follows:
// Only the changes are listed here
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
// Add a preCounter to record the previous props value
preCounter: 0.counter: 0}}static getDerivedStateFromProps(props, state) {
// Compare it to state.precounter
if(props.counter ! == state.preCounter) {return {
counter: props.counter,
preCounter: props.counter
}
}
return null
}
handleClick = () = > {
this.setState({
counter: this.state.counter + 1})}render() {
return (
<div>
<h1 onClick={this.handleClick}>Hello, world! {this.state.counter}</h1>
</div>)}}Copy the code
(3) the render
Render is the core method in React. A component must have this method. It renders the component according to its state and property, props. This function only does one thing, and that is to return the content to be rendered, so don’t do any other business logic inside this function. Usually calls to this function return one of the following types:
- React elements: This includes the native DOM and React components;
- Arrays and fragments: can return multiple elements.
- Portals: Child elements can be rendered to different DOM child trees.
- Strings and numbers: rendered as text nodes in the DOM;
- Boolean or NULL: nothing is rendered.
(4) componentDidMount ()
ComponentDidMount () is tuned immediately after the component is mounted (inserted into the DOM tree). The following operations are usually performed during this phase:
- Perform operations that depend on the DOM;
- Send network requests; (Official advice)
- Add subscription message (will unsubscribe at componentWillUnmount);
If setState is called in componentDidMount, it triggers an extra render, which is an extra call to render. The user is not aware of this because it is executed before the browser flusits the screen, but I should avoid this because it will cause some performance problems. Try to initialize the state object in Constructor.
After the component is loaded, change the count number to 1:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
counter: 0
}
}
componentDidMount () {
this.setState({
counter: 1
})
}
render () {
return (
<div className="counter">Counter value: {this.state.counter}</div>)}}Copy the code
2) Component update phase
When a component’s props change, or setState/forceUpdate is called internally, the update is triggered to be rerendered. This can happen multiple times. This phase calls the following methods in turn:
- getDerivedStateFromProps
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
- componentDidUpdate
(1) shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState)
Copy the code
Before we talk about this lifecycle function, let’s look at two questions:
- Does the setState function cause the component to rerender in any case? For example:
this.setState({number: this.state.number})
Copy the code
- If setState is not called, props does not change, so the component will not be rerendered?
The answer to the first question is yes. For the second question, if the parent component is rerendered, it will cause the child component to be rerendered regardless of whether the props are changed or not.
So is there a way to improve performance in these two scenarios without rerendering the components? This is the life cycle function shouldComponentUpdate that is used to speed things up. It is fired before the component is rerendered. By default, it returns true. Whether the this.state and nextState values have changed to determine whether true or false is returned. When false is returned, the component update process stops and subsequent Render and componentDidUpdate are not called.
Note: When adding the shouldComponentUpdate method, it is not recommended to use depth equality checking (such as using json.stringify ()), as deep comparisons are inefficient and may be less efficient than rerendering the component. Moreover, this method is difficult to maintain, so it is recommended to use this method when it can produce significant performance improvement.
(2) getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState)
Copy the code
This method is called after render and before componentDidUpdate. It takes two parameters, prevProps and prevState, to indicate the props and state before update. This function must be used with componentDidUpdate and has a return value, which defaults to NULL and is passed to componentDidUpdate as the third argument.
(3) the componentDidUpdate
ComponentDidUpdate () will be called immediately after the update and will not be executed for the first rendering. The following operations are usually performed during this phase:
- When the component is updated, operate on the DOM;
- If you compare props before and after the update, you can also choose to make a network request here; (For example, the network request will not be executed if the props have not changed).
componentDidUpdate(prevProps, prevState, snapshot){}
Copy the code
This method takes three arguments:
- PrevProps: props before the update
- PrevState: indicates the state before the update
- Snapshot: getSnapshotBeforeUpdate() Return value of the life cycle
3) Component uninstallation phase
The unload phase has only one lifecycle function, and componentWillUnmount() is called directly before the component is unloaded and destroyed. Perform the necessary cleanup in this method:
- Clear the timer, cancel the network request, or clear the timer
- Cancel subscriptions created in componentDidMount(), etc.
This life cycle is called before a component is unloaded and destroyed, so you should not use setState in this method because once the component is unloaded, it will not be loaded and will not be rerendered.
4) Error processing phase
ComponentDidCatch (Error, INFO), which is called after a descendant component throws an error. It receives two parameters:
- Error: An error is thrown.
- Info: An object with a componentStack key that contains stack information about a component throwing an error
React common life cycles are as follows:React common life cycle processes are as follows:
- In the mount phase, we first execute the constructor constructor to create the component
- Once created, the render method executes, which returns the content to be rendered
- React then mounts the content that needs to be rendered into the DOM tree
- Once the mount is complete, the componentDidMount lifecycle function is executed
- Render is called again if we create an props (for component communication), call setState (to change the data in state), or call forceUpdate (to force the component to update)
- After the render function is reexecuted, the DOM tree is remounted
- Once the mount is complete, the componentDidUpdate lifecycle function is executed
- When a component is removed, the componentWillUnmount lifecycle function is executed
React Main life cycle summary:
- GetDefaultProps: This function is called once (and only once) before the component is created. It is used to initialize the component’s Props;
- GetInitialState: Used to initialize the state value of the component;
- ComponentWillMount: After the component is created and before render, it goes to componentWillMount. I personally have not used this stage, very chicken ribs. Later React official has not recommended you do anything in componentWillMount, until now React16 directly abandoned the life cycle, it shows the extent of the cob;
- Render: This is the only method in all the lifecycle that you have to implement. React uses props and state to render the component to the interface. Sometimes, though, you might not want to render anything, in which case just have it return null or false;
- ComponentDidMount: Called immediately after the component is mounted (inserted into the DOM tree) to signal that the component is mounted. Some operations that depend on getting DOM node information will be done in this phase. Also, this is the time to make an Ajax request that is officially recommended by React. This method, like componentWillMount, is called once and only once.
2. What lifecycle does React scrap? Why is that?
The three functions that were deprecated were all before Render, and because of fber, it is likely that they will be executed multiple times due to the high priority tasks that interrupt the existing tasks. Another reason is that React wants to constrain users. A good framework can force people to write code that is easy to maintain and extend. Where to start
1) componentWillMount
This function can be used for constructor (componentDidMount). This function can be used for constructor (componentDidMount). This function can be used for constructor (constructor). If you subscribe to the willUnMount component, the willUnMount component will not be executed. If you subscribe to the willUnMount component, the willUnMount component will not be executed. If you subscribe to the willUnMount component, the willUnMount component will be executed. But users sometimes have to do things with componentWilMount for a variety of reasons, so React throws out the API in order to constrain developers
2) componentWillReceiveProps
In older versions of React, there was never an elegant way to update a component’s state if it was closely related to its props. You need to determine whether the two props are the same in componentWilReceiveProps. If they are different, update the new props to the corresponding state. Doing so destroys the single source of state data, making the state of the component unpredictable, and increasing the number of times the component is redrawn. There are many similar business requirements, such as a list that can be swiped horizontally, and when the currently highlighted Tab is clearly part of the list itself, it can directly navigate to a Tab based on a value passed in. To address these issues, React introduces the first new lifecycle: getDerivedStateFromProps. It has the following advantages:
- GetDSFP is a static method, so you can’t use this, which is a pure function, and you can’t write side effects
- The developer can only use prevState instead of prevProps to make comparisons. This ensures a simple relationship between state and props and does not have to deal with the case where prevProps is null on the first render
- Based on the first point, separating state changes (setState) from expensive operations (tabChange) makes it easier to operate, or optimize, the Render and COMMIT phases.
3) componentWillUpdate
Like componentWillReceiveProps, many developers will be according to the variation of props in componentWillUpdate to trigger some callback. Either componentWilReceiveProps or componentWilUpdate can be called multiple times during an update, which means that the callback function written here can also be called multiple times, which is obviously not desirable. (componentDidUpdate) (componentDidUpdate) (componentDidUpdate) (componentDidUpdate) So moving the callback originally written in componentWillUpdate to componentDidUpdate solves this problem.
In another case, the DOM element state needs to be obtained, but because render can be interrupted in Fber, the element state obtained in wilMount may be different from the actual need. This can usually be resolved using the second new life function getSnapshotBeforeUpdate(prevProps, prevState)
4) getSnapshotBeforeUpdate(prevProps, prevState)
Returns the value as the third parameter to componentDidUpdate. Unlike willMount, getSnapshotBeforeUpdate is executed before the final render execution, ensuring that the element state it obtains is the same as the element state obtained in didUpdate. Official reference code:
class ScrollingList extends React.Component {
constructor(props) {
super(props);
this.listRef = React.createRef();
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Do we add new items to the list?
// Capture the scroll position so that we can adjust the scroll position later.
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// If snapshot has a value, we just added a new item,
// Adjust the scroll position so that the new items don't push the old items out of the view.
// (Snapshot here is the value returned by getSnapshotBeforeUpdate)
if(snapshot ! = =null) {
const list = this.listRef.current; list.scrollTop = list.scrollHeight - snapshot; }}render() {
return (
<div ref={this.listRef}>{/ *... contents... * /}</div>); }}Copy the code
3. React 16.x props for handling changes in the lifecycle
This is handled in getDerivedStateFromProps.
The life cycle function is to replace componentWillReceiveProps exist, so the need to use componentWillReceiveProps, can consider to use getDerivedStateFromProps for replacement.
The arguments are different, and getDerivedStateFromProps is a static function. This means that this function cannot access the class properties, and direct access to the properties is not recommended. Instead, we should look at the nextProps and prevState provided by the arguments, and map to state based on the newly passed props.
Note that if the contents of the props are passed do not need to affect your state, then you need to return null. This is required, so try to write it at the end of the function:
static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// Update the state when the passed type changes
if(type ! == prevState.type) {return {
type,
};
}
// Otherwise, do nothing about state
return null;
}
Copy the code
4. React performance optimization in which lifecycle? How does it optimize?
A rerendering of the React parent’s Render function causes a rerendering of the child’s render method. However, sometimes the child component accepts data from the parent without changing. The execution of the child render component can affect performance, and shouldComponentUpdate can be used to address this.
The use method is as follows:
shouldComponentUpdate(nexrProps) {
if (this.props.num === nexrProps.num) {
return false
}
return true;
}
Copy the code
ShouldComponentUpdate provides two parameters, nextProps and nextState, for the nextProps and the nextState. When the function returns false, the render() method will not execute, and the component will not render. When the function returns true, The component is rerendered as usual. This method compares the value of the current props to the value of the next props. Return false if the values are equal, and true if not.
If the data type is referenced, it will be true even if the content of the data is changed, as long as the address of the data reference is not changed.
To solve this problem, we can use the following methods: (1) Use ES6 assgin to copy the data before using setState, but assgin only deep copies the first layer of the data, so it is not the most perfect solution:
const o2 = Object.assign({},this.state.obj)
o2.student.count = '00000';
this.setState({
obj: o2,
})
Copy the code
(2) Use json.parse (json.stringfy ()) for deep copy, but error when data is undefined and functions.
const o2 = JSON.parse(JSON.stringify(this.state.obj))
o2.student.count = '00000';
this.setState({
obj: o2,
})
Copy the code
5. What is the difference between the lifecycle of updates triggered by state and props?
State update process: Functions involved in this process:
- ShouldComponentUpdate: This lifecycle function is fired first when a component’s state or props change. It takes two arguments: nextProps and nextState — they represent the new props and the new state values passed in, respectively. With these two values in hand, we can use some contrast logic to determine whether re-render is necessary. If the return value of this function is false, the life cycle terminates, and vice versa;
Note: This method exists only as a way to optimize performance. Do not attempt to rely on this method to “block” rendering, as this can cause bugs. Consider using the built-in PureComponent instead of writing shouldComponentUpdate() manually
- ComponentWillUpdate: componentWillUpdate is called when a component’s state or props change before rendering. ComponentWillUpdate is one of three life cycles deprecated by React16. In the past, we might have wanted to gather the necessary information (such as the DOM information before the update, etc.) at this stage, but now we can do this entirely in React16’s getSnapshotBeforeUpdate;
- ComponentDidUpdate: componentDidUpdate() is called immediately after the UI is updated. It takes the props (the last props) as an input, which means we can still compare props at this point.
Props update process: Relative to the state update, props updated the only difference is added to componentWillReceiveProps calls. On the componentWillReceiveProps, need to know these things:
- ComponentWillReceiveProps: it is triggered when Component receive the new props. ComponentWillReceiveProps receives a parameter called nextProps corresponding new props (value). This lifecycle is one of three discarded by React16. Before it is deprecated, you can use it to reset the state by comparing this. Props to nextProps. In React16, replace it with a similar new lifecycle, getDerivedStateFromProps.
6. In what lifecycle should a network request be made in React? Why is that?
For asynchronous requests, it is best to put in componentDidMount to operate, for synchronous state changes, can be put in componentWillMount, generally used less.
It would be a mistake to think that making a request in componentWillMount can get results early. Usually componentWillMount is not much more than a microsecond earlier than componentDidMount, and any delay on the network is negligible.
Constructor () -> componentWillMount() -> render() -> componentDidMount()
The above methods are called sequentially, from the top down.
- Constructor is called at the beginning when the component is ready to be mounted before it has been mounted to the web page.
- ComponentWillMount method calls after the constructor, before render the code in this method call setState method not trigger to render, so it does not generally used for loading data.
- The code in the componentDidMount method is invoked only after the component has been fully mounted to the web page, so the data is guaranteed to be loaded. In addition, calling the setState method in this method triggers a re-render. Therefore, the official design of this method is used to load external data, or handle other side effects of the code. Loading irrelevant to the data on the component, can also be done in Constructor, but constructor is to do the component state initialization work, not to do the load data this work, can not setState in constructor, and the loading time is too long or error, the page can not be loaded out. So any code that has side effects will be concentrated in the componentDidMount method.
Conclusion:
- If the data is fetched in componentWillMount, the fetch data will be executed twice, once on the server and once on the client. This is solved in componentDidMount, and componentWillMount will also render twice.
- Fetch data in componentWillMount, data must arrive after render, if you forget to set the initial state, the user experience is bad.
- After react16.0, componentWillMount may be executed multiple times.
7. What are the new life cycles in React 16
About the new lifecycle of React16 starting applications:As can be seen, React16 takes another dimension of the life cycle from top to bottom:
- Render phase: used to calculate some necessary state information. This phase may be paused by React, which is related to the Fiber architecture introduced by React16 (which we’ll focus on later);
- Pre-commit phase: By “commit,” I mean the action of “updating the real DOM node.” Pre-commit means I haven’t updated the real DOM yet, but the DOM information is already readable.
- Commit: At this stage, React finishes updating the real DOM. In the Commit phase, we can get the real DOM (including refs).
At the same time, the new lifecycle still follows the three broad divisions of “mount,” “update,” and “uninstall” in terms of process. They correspond to:
- Mounting process:
- constructor
- getDerivedStateFromProps
- render
- componentDidMount
- Update process:
- getDerivedStateFromProps
- shouldComponentUpdate
- render
- getSnapshotBeforeUpdate
- componentDidUpdate
- Unloading process:
- componentWillUnmount
Iv. Component communication
The following are common situations for React communication:
- The parent component communicates with the child component
- The child communicates with the parent
- Cross-level component communication
- Component communication without nested relationships
1. Communication mode between parent and child components?
Parent to child communication: The parent sends the required information to the child using props.
// Child component: Child
const Child = props= >{
return <p>{props.name}</p>
}
// The Parent component
const Parent = () = >{
return <Child name="react"></Child>
}
Copy the code
How the child communicates with the parent: : props+ callback.
// Child component: Child
const Child = props= >{
const cb = msg= >{
return () = >{
props.callback(msg)
}
}
return (
<button onClick={cb("Hello!" )} >hello</button>)}// The Parent component
class Parent extends Component {
callback(msg){
console.log(msg)
}
render(){
return <Child callback={this.callback.bind(this)}></Child>}}Copy the code
2. How do cross-level components communicate?
The parent component communicates to the children of the child component and to further child components:
- If the parent component has a deeper structure, then each of the intermediate components has to pass the props, adding complexity and not being needed by the intermediate component itself.
- When you use a context, a context is like a big container in which you can put the content that you want to communicate in, so that you can access it no matter how deep it is nested, and you can use a context for global data that spans multiple levels.
// The context mode implements cross-level component communication
// Context is designed to share data that is "global" to a tree of components
const BatteryContext = createContext();
// Subcomponents of subcomponents
class GrandChild extends Component {
render(){
return (
<BatteryContext.Consumer>
{
color => <h1 style={{"color":color}} >I am red :{color}</h1>
}
</BatteryContext.Consumer>)}}/ / child component
const Child = () = >{
return (
<GrandChild/>)}/ / the parent component
class Parent extends Component {
state = {
color:"red"
}
render(){
const {color} = this.state
return (
<BatteryContext.Provider value={color}>
<Child></Child>
</BatteryContext.Provider>)}}Copy the code
3. How do non-nested relationship components communicate?
That is, components that do not have any containment relationships, including sibling components and non-sibling components that are not in the same parent.
- Custom event communication can be used (publish-subscribe pattern)
- You can use redux to manage the global state
- If the communication is a sibling component, the common parent node of the two sibling nodes can be found, and the communication between father and son can be combined.
4. How to solve the problem of props being too deep
- Using the Context API: Provides a way to share state between components without passing props layer by layer through the explicit component tree;
- Use state libraries such as Redux.
5. What are the communication modes of components
- Parent to child: The parent component can communicate with the child component by passing props
- This function is a function that is scoped by the parent component itself. The child component calls this function, passing the information that the child component wants to pass as a parameter to the parent component’s scope
- Sibling component communication: Find the common parent node of the two sibling nodes, and use the above two methods to forward information by the parent node for communication
- Communication across layers: Context is designed to share data that is “global” to a tree of components, such as currently authenticated users, topics, or preferred languages, and is ideally suited for communicating global data across layers through Context
- Publish/subscribe pattern: Publishers publish events, subscribers listen to and react to events, and we can communicate by introducing the Event module
- Global state management tools: Communicate with global state management tools such as Redux or Mobx, which maintain a global state center Store and generate new states based on different events
Five, routing,
1. How does the React-Router work?
The idea of client-side routing implementation:
- Hash based routing: By listening
hashchange
Event to sense the hash change- You can change the hash directly by location.hash= XXX
- Routing based on H5 History:
- PushState, resplaceState, etc., which pushes the URL onto the stack and can be applied
history.go()
Such as API - Listening for url changes can be triggered by custom events
- PushState, resplaceState, etc., which pushes the URL onto the stack and can be applied
React-router implements the following ideas:
- Based on the
history
Library to implement the above different client routing implementation ideas, and can save history, etc., smooth browser differences, no upper layer awareness - Through the maintained list, every time the URL changes, through the configured route path, match to the corresponding Component, and render
2. How do I configure the React-router to implement route switchover
(1) Use<Route>
component
Route matching is achieved by comparing the path attribute of
with the pathname of the current address. When a
match succeeds, it renders its contents, and when it does not match, it renders null.
with no path will always be matched.
// when location = { pathname: '/about' }
<Route path='/about' component={About}/> // renders <About/>
<Route path='/contact' component={Contact}/> // renders null
<Route component={Always}/> // renders <Always/>
Copy the code
(2) Combined use<Switch>
The component and<Route>
component
is used to group
.
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
Copy the code
is not required for grouping
, but it is often useful. A
iterates through all of its child
elements and renders only the first element that matches the current address.
(3) Use<Link>, <NavLink>, <Redirect>
component
component to create links in your application. Wherever you render a , the anchor () is rendered in the HTML of the application.
<Link to="/">Home</Link>
// <a href='/'>Home</a>
Copy the code
Is a special type that can be defined as “active” when its to attribute matches the current address.
// location = { pathname: '/react' }
<NavLink to="/react" activeClassName="hurray">
React
</NavLink>
// <a href='/react' className='hurray'>React</a>
Copy the code
We can render a
when we want to force navigation, and when a
is rendered, it will use its to attribute for orientation.
3. How to set redirection on react-router?
Use the
component to Redirect routes:
<Switch>
<Redirect from='/users/:id' to='/users/profile/:id'/>
<Route path='/users/profile/:id' component={Profile}/>
</Switch>
Copy the code
When the request /users/:id is redirected to ‘/users/profile/:id’ :
- attribute
from: string
: The path that needs to be matched will be redirected. - attribute
to: string
: The redirected URL string - attribute
to: object
: Redirects the Location object - attribute
push: bool
: If true, the redirection will add the new address to the visit history, and there is no way to go back to the previous page.
4. The difference between Link tag and A tag in react-Router
is the default Link behavior of the react-router.
is the default Link behavior of the react-router. The “jump” behavior of
only triggers the page content update corresponding to the matching
, but does not refresh the entire page.
Did three things:
- If you have onclick, do onclick
- Block the a tag default event when click
- Based on the jump href(that is, to), use history (one of the two methods of web front-end routing, history & Hash) to jump to the page. This time, only the link changes, but the page does not refresh
<a>
A tag is a normal hyperlink, used to jump from the current page to another page that the href points to (in the case of a non-anchor point).
What did you do to make the jump after the a TAB default event was disabled?
let domArr = document.getElementsByTagName('a')
[...domArr].forEach(item= >{
item.addEventListener('click'.function () {
location.href = this.href
})
})
Copy the code
5. How to get URL parameters and history objects from react-router?
(1) Obtain the URL parameters
- Get the value
Route configuration or common configuration, such as ‘admin’, and parameter transmission mode, such as ‘admin? Id = ‘1111’ ‘. Through this. Props. The location. The search for access to a url string ‘? Id =’1111’ can be resolved using urls, QS, QueryString, the browser API URLSearchParams object, or its own encapsulated methods.
- Dynamic routing value transmission
The route must be configured as a dynamic route, such as path=’/admin/:id’, and the parameter transmission mode, such as ‘admin/111’. Through this. Props. Match. Params. Id to obtain the value of the dynamic routing id part of the url in addition can also through useParams (Hooks) to obtain
- Pass values by query or state
For example, in the Link component’s to property, you can pass an object {pathname:’/admin’,query:’111′,state:’111′}; . By enclosing props. The location. The state or enclosing props. The location. The query to retrieve, the parameters of the transmission can be the object, array, etc., but there is just refresh the page and parameters will be lost.
(2) Obtain the history object
- If React >= 16.8 you can use the Hooks provided in the React Router
import { useHistory } from "react-router-dom";
let history = useHistory();
Copy the code
2. Use this.props. History to get the history object
let history = this.props.history;
Copy the code
6. How can react-Router 4 rerender the same component when the route changes?
When routing change, the components of props has changed, will be called componentWillReceiveProps life cycle such as hook. All that needs to be done is: When the route changes, according to the route, also request the data:
class NewsList extends Component {
componentDidMount () {
this.fetchData(this.props.location);
}
fetchData(location) {
const type = location.pathname.replace('/'.' ') | |'top'
this.props.dispatch(fetchListData(type))
}
componentWillReceiveProps(nextProps) {
if(nextProps.location.pathname ! =this.props.location.pathname) {
this.fetchData(nextProps.location); } } render () { ... }}Copy the code
ComponentWillReceiveProps using life cycle, to render the preprocessing operations.
7. How many modes are there for react-router routing?
React-router supports both hash (hash Router) and Browser (BrowserRouter) routing rules. React-router-dom provides two components, BrowserRouter and HashRouter, to synchronize the UI and URL of an application:
- BrowserRouter Created URL format: xxx.com/path
- HashRouter Creates a URL in the format of xxx.com/#/path
(1) BrowserRouter
It uses the HISTORY API provided by HTML5 (pushState, replaceState, and PopState events) to keep the UI and URL synchronized. The BrowserRouter uses HTML 5’s History API to control routing:
<BrowserRouter
basename={string}
forceRefresh={bool}
getUserConfirmation={func}
keyLength={number}
/>
Copy the code
The attributes are as follows:
- Basename Indicates the base URL of all routes. The correct format for basename is to have a leading slash, but not a trailing slash;
<BrowserRouter basename="/calendar">
<Link to="/today" />
</BrowserRouter>
Copy the code
Is equivalent to
<a href="/calendar/today" />
Copy the code
- ForceRefresh if true, the entire page will refresh during navigation. In general, use this feature only in browsers that do not support the HTML5 History API;
- GetUserConfirmation is a function to confirm the navigation. The default is window.confirm. For example, when navigating from /a to /b, the default confirm function will pop up a prompt, and the user will click OK to navigate. Otherwise, nothing will be done.
// This is the default validation function
const getConfirmation = (message, callback) = > {
const allowTransition = window.confirm(message);
callback(allowTransition);
}
<BrowserRouter getUserConfirmation={getConfirmation} />
Copy the code
Need to be used with
.
- KeyLength is used to set the length of the location. Key.
(2) HashRouter
Use the hash part of the URL (window.location.hash) to keep the UI and URL synchronized. A HashRouter controls routing through the hash attribute of the URL:
<HashRouter
basename={string}
getUserConfirmation={func}
hashType={string}
/>
Copy the code
Its parameters are as follows:
- The basename getUserConfirmation and
BrowserRouter
Function the same; - HashType Window.location. hash Hash type used. The hash types are as follows:
- Slash – followed by a slash, such as #/ and #/sunshine/lollipops;
- Noslash – no trailing slash, such as # and #sunshine/lollipops;
- Hashbang – Google-style Ajax crawlable such as #! / and #! / sunshine/lollipops.
8. What’s the use of the React-Router 4 Switch?
The Switch is usually used to wrap a Route. It is used to render the first child
or
that matches the path, and no other elements can be placed inside it.
If
is not added:
import { Route } from 'react-router-dom'
<Route path="/" component={Home}></Route>
<Route path="/login" component={Login}></Route>
Copy the code
The path attribute of the Route component is used to match the path, because you need to match/to Home and /login to login, so you need two routes, but you can’t write them like this. If the URL path is “/login”, both
to display only one matching component:
import { Switch, Route} from 'react-router-dom'
<Switch>
<Route path="/" component={Home}></Route>
<Route path="/login" component={Login}></Route>
</Switch>
Copy the code
At this point, when the /login path is accessed again, only the Home component is displayed. This is where the exact attribute is used. It is used to exactly match paths and is often used in conjunction with
.
< path >
import { Switch, Route} from 'react-router-dom'
<Switch>
<Route exact path="/" component={Home}></Route>
<Route exact path="/login" component={Login}></Route>
</Switch>
Copy the code
Note: Due to the word limit of the article, please see the next part for the rest of the content.