Author: Alex
Translator: Front-end wisdom
Source: dev. To
The more you know, the more you don’t know
Like it and see. Make it a habit
GitHub: github.com/qq449245884… Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.
Question 1: What is the virtual DOM?
Theme: the React
Difficulty: ⭐
The virtual DOM (VDOM) is an in-memory representation of the real DOM. The REPRESENTATION of the UI is kept in memory and synchronized with the actual DOM. This is a step that takes place between the rendering function being called and the element being displayed on the screen, and the whole process is called reconciliation.
Question 2: What is the difference between a class component and a function component?
Theme: the React
Difficulty: ⭐ ⭐
-
Class components can use other features, such as state States and lifecycle hooks.
-
A stateless component is a functional component when it simply receives props rendering to the page. It is also called a dumb component or presentation component.
Of course, there is a difference between a function component and a class component, and the performance of a function component is higher than that of a class component, because a class component is instantiated when it is used, whereas a function component simply executes the function and returns the result. To improve performance, use functional components whenever possible.
The difference between | Function component | Class components |
---|---|---|
Is there athis |
There is no | There are |
Whether there is a life cycle | There is no | There are |
Stateful or notstate |
There is no | There are |
Question 3: What is refs used for in React?
Theme: the React
Difficulty: ⭐ ⭐
Refs provides a way to access DOM nodes or React elements created in the Render method. In a typical data flow, props is the only way parent-child components can interact, and to modify the child component, you need to re-render it with new Pros. There are exceptions to this rule, and in some cases we need to force changes to children outside of the typical data stream. Refs can be used in this case.
We can use this by adding a ref attribute to the component, whose value is a callback function that receives the underlying DOM element or mount instance of the component as its first argument.
class UnControlledForm extends Component {
handleSubmit = () => {
console.log("Input Value: ", this.input.value)
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
ref={(input) => this.input = input} />
<button type='submit'>Submit</button>
</form>
)
}
}
Copy the code
Notice that the input element has a ref attribute whose value is a function. The function takes the actual DOM element of the input and places it on the instance so that it can be accessed inside the handleSubmit function.
It is often misunderstood that refs can only be used in class components, but refs can also be used with function components by utilizing closures in JS.
function CustomForm ({handleSubmit}) {
let inputElement
return (
<form onSubmit={() => handleSubmit(inputElement.value)}>
<input
type='text'
ref={(input) => inputElement = input} />
<button type='submit'>Submit</button>
</form>
)
}
Copy the code
Question 4: How do you handle events in React
Theme: the React
Difficulty: ⭐ ⭐
To address cross-browser compatibility issues, SyntheticEvent instances will be passed to your event handlers. SyntheticEvent is the React cross-browser browser native event wrapper and has the same interface as browser native events. This includes stopPropagation() and preventDefault().
Interestingly, React doesn’t actually attach events to the child nodes themselves. React uses a single event listener to listen for all events at the top level. This is good for performance and means React doesn’t need to track event listeners when updating the DOM.
Question 5. What is the difference between state and props?
Theme: the React
Difficulty: ⭐ ⭐
Props and state are plain JS objects. Although they both contain information that affects the rendered output, their component-wise functionality is different. namely
state
Components manage their own data, control their own state, variable;props
Is an external data parameter, immutable;- There is no
state
The stateless component is called the stateless componentstate
Are called stateful components; - multi-purpose
props
Use less,state
That is, write more stateless components.
Question 6: How do I create refs
Theme: the React
Difficulty: ⭐ ⭐
Refs are created using react.createref () and attached to the React element via the ref attribute. When components are constructed, Refs are typically assigned to instance properties so that they can be referenced throughout the component.
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; }}Copy the code
Or use it this way:
class UserForm extends Component {
handleSubmit = () => {
console.log("Input Value is: ", this.input.value)
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
ref={(input) => this.input = input} /> // Access DOM input in handle submit
<button type='submit'>Submit</button>
</form>
)
}
}
Copy the code
Q7: What is a higher-order component?
Theme: the React
Difficulty: ⭐ ⭐
HOC is a function that takes a component and returns a new one. Basically, this is a pattern derived from the composite features of React, calling them pure components because they can accept any dynamically supplied subcomponents without modifying or copying any behavior in the input components.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
Copy the code
HOC can be used in many of the following use cases
- Code reuse, logic, and bootstrap abstraction
- Rendering hijacked
- State abstractions and operations
- Props to deal with
Problem 8: In the constructor callsuper
And will beprops
What does passing in as a parameter do?
Theme: the React
Difficulty: ⭐ ⭐
The subclass constructor cannot use this reference until the super() method is called, as is the case with ES6 subclasses. The main reason for passing the props argument to the super() call is that in the subconstructor we can get the props passed through this.props.
Pass props
class MyComponent extends React.Component {
constructor(props) {
super(props);
console.log(this.props); // { name: 'sudheer',age: 30 }
}
}
Copy the code
Don’t pass props
class MyComponent extends React.Component { constructor(props) { super(); console.log(this.props); // undefined // but console.log(Props) is still available; // Prints {name: 'sudheer',age: 30}} render() {// constructor external not affected console.log(this.props) // {name: 'sudheer',age: 30 30}}}Copy the code
The above example illustrates one point. The behavior of the props is different only inside the constructor and outside the constructor.
Question 9: What is a control component?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
In HTML, form elements such as ,
React works differently. The component that contains the form tracks the input value in its state and rerenders the component every time a callback function (such as onChange) fires, as the state is updated. The input form elements whose values are controlled by React in this way are called controlled components.
Question 10. How about react.createElement?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
Question:
const element = (
<h1 className="greeting">
Hello, world!
</h1>
)
Copy the code
This code is implemented using react. createElement:
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
Copy the code
11. What is JSX?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
When Facebook first released React, they also introduced a new JS dialect, JSX, that embedded raw HTML templates into JS code. The JSX code itself cannot be read by browsers and must be converted to traditional JS using tools such as Babel and Webpack. Many developers will be able to use JSX unconsciously because it’s already integrated with React.
class MyComponent extends React.Component { render() { let props = this.props; return ( <div className="my-component"> <a href={props.url}>{props.name}</a> </div> ); }}Copy the code
12. Can the two problems be identified according to the code defined below?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
Take a look at the following code:
The answer:
1. The constructor does not pass props to super, which should include the following line
constructor(props) {
super(props);
// ...
}
Copy the code
2. The scope of the event listener (when allocated via addEventListener()) is incorrect because ES6 does not provide automatic binding. Therefore, developers can reassign clickHandler in the constructor to include the correct binding:
constructor(props) {
super(props);
this.clickHandler = this.clickHandler.bind(this);
// ...
}
Copy the code
13. Why not update directlystate
?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
If you try to update state directly, the component will not be rerendered.
// error this.state. message = 'Hello world';Copy the code
The setState() method is used to update the state. It schedules updates to the component state object. When state changes, the component responds by rerendering:
This.setstate ({message: 'Hello World'});Copy the code
Question 14: What are the different phases of the React component life cycle?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
There are four distinct phases in the component lifecycle:
-
Initialization: During this phase, the component is ready to set its Initialization state and default properties.
-
Mounting: The React component is ready to mount to the browser DOM. This phase includes the componentWillMount and componentDidMount lifecycle methods.
-
Updating: During this phase, the component is updated in two ways, sending the new props and state. This phase includes shouldComponentUpdate, componentWillUpdate, and componentDidUpdate lifecycle methods.
-
Unmounting: At this stage, the component is no longer needed and is unmounted from the browser DOM. This phase contains the componentWillUnmount lifecycle method.
In addition to the four common life cycles above, there is another error-handling phase:
Error Handling: At this stage, this component is invoked whether an Error occurs during rendering, in a lifecycle method, or in the constructor of any child component. This phase contains the componentDidCatch lifecycle method.
15. What are the React lifecycle methods?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
-
ComponentWillMount: Executed before rendering for app-level configuration in the root component.
-
ComponentDidMount: Executed after the first rendering, this is where you can make AJAX requests, DOM manipulation or status updates, and set up event listeners.
-
ComponentWillReceiveProps: do not perform when initializing render, it will undergo in the component to the new state (Props) is triggered, commonly used in the parent component state update subcomponents of rendering
-
ShouldComponentUpdate: Determines whether to update the component. By default, it returns true. If it is determined that the component does not need to be re-rendered after the state or props update, return false, which is a way to improve performance.
-
ComponentWillUpdate: Executed before shouldComponentUpdate returns true to determine the component to be updated.
-
ComponentDidUpdate: This is primarily used to update the DOM in response to props or state changes.
-
ComponentWillUnmount: This is used to cancel any network requests or remove any event listeners associated with the component.
Question 16: The three points (…) What does React do?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
. What do I do in React code? What is it called?
<Modal {... this.props} title='Modal heading' animation={false}/>Copy the code
This is called the extension operator or expansion operator, for example, if this.props contains a: 1 and b: 2, then
<Modal {... this.props} title='Modal heading' animation={false}>Copy the code
Equivalent to the following:
<Modal a={this.props.a} b={this.props.b} title='Modal heading' animation={false}>
Copy the code
Not only does the extension notation work for this use case, it’s also handy for creating new objects that have most (or all) of the properties of existing objects, as we often do when updating state:
this.setState(prevState => { return {foo: {... prevState.foo, a: "updated"}}; });Copy the code
17. What are the benefits of using React Hooks?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
First, Hooks generally enable extraction and reuse of stateful logic that is common across multiple components without the burden of higher-order components or rendering props. Hooks can easily manipulate the state of function components without needing to convert them to class components.
Hooks do not work on classes. By using them, you can completely avoid using life cycle methods such as componentDidMount, componentDidUpdate, componentWillUnmount. Instead, use built-in hooks like useEffect.
Question 18. What are React Hooks?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
Hooks are new additions in React 16.8. They allow the use of state and other React features without writing classes. Using Hooks, you can extract stateful logic from components so that it can be tested and reused independently. Hooks allow us to reuse stateful logic without changing the component hierarchy, making it easy to share Hooks between many components or with the community.
Question 19: In ReactuseState()
What is?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
Here’s what useState(0) is for:
. const [count, setCounter] = useState(0); const [moreStuff, setMoreStuff] = useState(...) ; . const setCount = () => { setCounter(count + 1); setMoreStuff(...) ; . };Copy the code
UseState is a built-in React Hook. UseState (0) returns a tuple where the first argument count is the current state of the counter, and setCounter provides methods to update the state of the counter.
We can use the setCounter method to update the count state anywhere – in this case, we can do more with it inside the setCount function. Using Hooks keeps our code more functional and avoids using class-based components too much.
Question 20. What is StrictMode in React?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
StrictMode
-
Verify that internal components follow certain recommended practices and, if not, issue a warning on the console.
-
Verify that deprecated methods are used and, if so, warn the console.
-
Prevent some side effects by identifying potential risks.
Question 21: Why do class methods need to be bound to class instances?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
In JS, the value of this changes depending on the current context. In the React class component methods, developers typically want this to refer to the current instance of the component, so it’s necessary to bind these methods to the instance. Normally this is done in a constructor:
class SubmitButton extends React.Component {
constructor(props) {
super(props);
this.state = {
isFormSubmitted: false
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit() {
this.setState({
isFormSubmitted: true
});
}
render() {
return (
<button onClick={this.handleSubmit}>Submit</button>
)
}
}
Copy the code
22. What is Prop Drilling and how can it be avoided?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
When building a React application, you nest components in multiple layers to use data provided by another nested component. The simplest way to do this is to pass a prop layer by layer from each component, from the source component to the deep nested component. This is called Prop Drilling.
The main disadvantage of Prop Drilling is that components that do not require data become unnecessarily complex and difficult to maintain.
To avoid prop drilling, a common approach is to use React Context. By defining a Provider component that provides the data, and allowing nested components to useContext data through the Consumer component or useContext Hook.
Question 23: Describe Flux versus MVC?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
The traditional MVC pattern works well in separating data (Model), UI(View, and logic (Controller), but the MVC architecture often runs into two major problems:
Data flow is not clear: Cascading updates across views often result in a chaotic web of events that are difficult to debug.
Lack of data integrity: Model data can mutate anywhere, resulting in unpredictable results throughout the UI.
Complex user interfaces using Flux mode are no longer subject to cascading updates, and any given React component is able to reconstruct its state from the data provided by the Store. The Flux pattern also enforces data integrity by limiting direct access to shared data.
Question 24. What is the difference between a controlled component and an uncontrolled component?
Theme: the React
Difficulty: ⭐ ⭐ ⭐
- The managed component is the component in React control and is the only real source of form data.
- The uncontrolled component is where the DOM processes the form data, not in the React component.
Although uncontrolled components are usually easier to implement because you can simply use refs to get values from the DOM, it is often recommended to choose controlled components over uncontrolled ones.
The main reason for this is that the controlled component supports instant field validation, allows conditionally disabling/enabling buttons, and enforces input formats.
Question 25: What’s wrong with this code?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
What’s wrong with this code:
this.setState((prevState, props) => {
return {
streak: prevState.streak + props.count
}
})
Copy the code
The answer:
There is no problem. This is rarely used. We can pass a function to setState that takes the value of the previous state and the current props and returns a new state. This is recommended if we need to reset the state based on the previous state.
Question 26. What is React Context?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
Context provides a way to pass data through the component tree, eliminating the need to manually pass props properties at every level.
27. What is React Fiber?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
Fiber is the new coordination engine or re-implementation of the core algorithm in React 16. Its main goal is to support incremental rendering of the virtual DOM. React Fiber aims to improve its applicability in areas such as animation, layout, gestures, pause, pause, or reuse, and assign priority to different types of updates, as well as new concurrency primitives.
React Fiber aims to enhance its applicability in areas such as animation, layout, and gestures. Its main feature is incremental rendering: the ability to split the rendering effort into chunks and spread it out over multiple frames.
Question 28: How do I apply validation to Props of ReactJS?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
When the application is running in development mode, React will automatically check all props we set up on the component to make sure they have the correct data type. For incorrect types, warning messages are generated in the console in development mode and disabled in production mode due to performance impact. The mandatory props is defined with isRequired.
Here is a set of predefined prop types:
- React.PropTypes.string
- React.PropTypes.number
- React.PropTypes.func
- React.PropTypes.node
- React.PropTypes.bool
For example, we define the following propTypes for the user component
import PropTypes from 'prop-types';
class User extends React.Component {
render() {
return (
<h1>Welcome, {this.props.name}</h1>
<h2>Age, {this.props.age}
);
}
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
};
Copy the code
Question 29. What is the difference between using the constructor in React and getInitialState?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
The difference between the constructor and getInitialState is between ES6 and ES5 itself. When using ES6 classes, you should initialize state in the constructor and define the getInitialState method when using React. CreateClass.
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state */ }; }}Copy the code
Is equivalent to:
var MyComponent = React.createClass({ getInitialState() { return { /* initial state */ }; }});Copy the code
Question 30: How do I conditionally add properties to the React component?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
React is smart enough to omit certain properties if the value passed to it is imaginary. Such as:
var InputComponent = React.createClass({ render: function() { var required = true; var disabled = false; return ( <input type="text" disabled={disabled} required={required} /> ); }});Copy the code
Render result:
<input type="text" required>
Copy the code
Another possible approach is:
var condition = true; var component = ( <div value="foo" { ... ( condition && { disabled: true } ) } /> );Copy the code
Question 31: Hooks will replace themrender props
And higher-order components?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
In general, the render props and higher-order components only render a child component. The React team believes that Hooks are an easier way to service this use case.
There is still room for both patterns (for example, a virtual Scroller component might have a renderItem prop, or a visual container component might have its own DOM structure). But in most cases, Hooks are sufficient to help reduce nesting in the tree.
Question 32: How do I avoid rerendering components?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐
One of the most common problems with React is that components unnecessarily rerender. React provides two methods that are useful in these situations:
-
React.memo(): This prevents unnecessary re-rendering of function components
-
PureComponent: This prevents unnecessary re-rendering of class components
Both methods rely on a shallow comparison of the props passed to the component, and if the props are not changed, the component will not be rerendered. While both tools are useful, shallow comparisons can lead to an additional performance penalty, so both can have a negative impact on performance if used improperly.
Using the React Profiler, you can measure performance before and after using these methods to ensure that you are actually improving performance by making a given change.
Question 33: What is a pure function?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐ ⭐
A pure function is a function that does not depend on and does not change the state of a variable outside its scope. Essentially, pure functions always return the same result given the same parameters.
Question 34: When calledsetState
When the Reactrender
How does it work?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐ ⭐
We can divide “render” into two steps:
-
Virtual DOM Rendering: When the Render method is called, it returns the virtual DOM structure of a new component. When setState() is called, render is called again, because shouldComponentUpdate always returns true by default, so React is not optimized by default.
-
Native DOM rendering :React only modifies real DOM nodes in the virtual DOM, and only infrequently — this is a great React feature that optimizes changes to the real DOM and makes React faster.
Question 35: How do I avoid rebinding instances in React?
Theme: the React
Difficulty: ⭐ ⭐ ⭐ ⭐ ⭐
There are several common ways to avoid binding methods in React:
1. Define event handlers as inline arrow functions
class SubmitButton extends React.Component {
constructor(props) {
super(props);
this.state = {
isFormSubmitted: false
};
}
render() {
return (
<button onClick={() => {
this.setState({ isFormSubmitted: true });
}}>Submit</button>
)
}
}
Copy the code
2. Use arrow functions to define methods:
class SubmitButton extends React.Component {
state = {
isFormSubmitted: false
}
handleSubmit = () => {
this.setState({
isFormSubmitted: true
});
}
render() {
return (
<button onClick={this.handleSubmit}>Submit</button>
)
}
}
Copy the code
3. Use function components with Hooks
const SubmitButton = () => {
const [isFormSubmitted, setIsFormSubmitted] = useState(false);
return (
<button onClick={() => {
setIsFormSubmitted(true);
}}>Submit</button>
)
};
Copy the code
The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.
Original: www.gangboard.com/blog/reactj…
communication
Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.
This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.