react face to face

React interview questions 

create a react project

1. Install create-react-app globally
npm install -g create-react-app
2. Create a project
create-react-app myapp
3. Partial installation, you can use npx directly
npx create-react-app myapp
4. Enter the folder
cd myapp
5. Enable the project
npm start (run in development mode)
npm test (test environment running)
npm run build (packaged for production mode)
6. Display configuration file: irreversible, as long as it is displayed, there is no way to hide it back
npm run eject

 It takes a while to wait here, actually three things will be installed

  • react: the top-level library for react
  • react-dom: Because react has many operating environments, such as react-native on the app side, we use react-dom to run on the web
  • react-script: Contains all scripts and configurations for running and packaging react applications 

1. What is React?

A JS library for constructing user interfaces 

2. What are the characteristics of React? (What are the main functions of react?)

It is used for virtual DOM, component design pattern, declarative code, one-way data flow, using jsx to describe information, etc.

3. What is the component design pattern?

Reusable code can be extracted into components for common use (UI, methods, etc.) 

4. Declarative code (programming) thinking:

Just explain your purpose, and then don't specify how to do it.

Example: Go to the bar and tell the waiter that you want a cocktail, and the waiter will give you the prepared cocktail without saying what the process is like
const toLowerCase = arr = arr.map(
    value => value.toLowerCase();
)

5. Are there other programming methods?

Imperative programming: It is to describe how the code works, tell the computer to execute step by step, what to do first and then what to do.

Example: Go to a bar to order a glass of wine and direct the waiter

remove a glass from the shelf
put the glass before the barrel
Turn on the barrel switch until the wine glass is full
Pass the finished cocktail to the customer
const toLowerCase = arr => {
    const res = [];
    for (let i = 0, len = arr.length; i < len; i++) {
        res.push(arr[i].toLowerCase());
    }
    return res;
}

6. Several methods of React event processing (how to create an event)

import React from 'react'
class Test extends React.Component{
    
    handleClick2(){
        console.log('click2')
    }

    hangleClick4 = () =>{
        console.log('click4')
    }
    render(){
        return(
            <button onClick={ console.log('click1')}>click1</button>
            <button onClick={ this.handleClick2.bind(this)}>click2</button>
            <button onClick={ () => {console.log('click3')}>click3</button>
            <button onClick={ this.hangleClick4 }>click3</button>
        )
    }
}
export default Test

 66. Introduce the process of Redux data flow (important)

How does Redux implement communication between multiple components, and how multiple components use the same state to manage  

redux is a js state container

work process:

  • View will dispatch action method in redux
  • The action will be dispatched to the store through the dispatch method of the store
  • The store receives the action, together with the previous state, and passes it to the reducer
  • The reducer returns new data to the store
  • store to change its own state

Redux - Detailed Explanation_Mr. Fingertip Dancer's Blog-CSDN Blog_redux

Redux principle and workflow_QcoY_的博客-CSDN Blog_redux workflow

67. Hooks are commonly used 

useEffct uses:
If no parameters are passed: it will be executed after rendering
Passing parameters is an empty array: equivalent to componentDidMount
If passing an array: equivalent to componentDidUpdate
If it returns: equivalent to componentWillUnmount
Cleanup will be performed when the component is unmounted. The effect is executed every time it is rendered. React will clear the previous effect before executing the current effect.

useLayoutEffect:
useLayoutEffect is executed before the browser renders
useEffect is executed after the browser renders

When the parent component introduces the child component and updates the state of a certain value, it often causes some unnecessary waste.
The emergence of useMemo and useCallback is to reduce this waste and improve the performance of components.
The difference is: useMemo returns a cached value, that is, a memoized value, while useCallback returns a memoized callback function.


useCallback
When the parent component updates the child component, it will be rendered, and the method will not be executed repeatedly, and the wrapping function will return the function;

useMemo:
const memoizedValue =useMemo(callback,array)
callback is a function for processing logic
array Control the array to re-execute useMemo, useMemo will be re-executed only when the array changes
If the array is not passed, it will be recalculated every time it is updated
Empty array, will only be calculated once
Rely on the corresponding value, when the corresponding value changes, it will be recalculated (you can rely on the value returned by another useMemo)
Side effect logic processing cannot be written in useMemo, the logic processing of side effects is processed in useEffect

custom hook
A custom Hook is a function whose name starts with "use", and other Hooks can be called inside the function.
Custom Hook is a convention that naturally follows Hook design, not a feature of React
In my opinion, custom hook is to write a piece of business logic separately.

 const [counter, setCounter] = useState(0);
 const counterRef = useRef(counter); // can save the last variable

useRef get node
function App() {
    const inputRef = useRef(null);

    return <div>
        <input type="text" ref={inputRef}/>
        <button onClick={() => inputRef.current.focus()}>focus</button>
    </div>
}

7. What is unidirectional data flow 

Data is mainly passed from parent nodes to child nodes (via props). If a props of the parent changes, React will re-render all child nodes

If the child component wants to modify the value of the parent-child component, how should it be done?
As follows: event event, the child component cannot modify the value of the parent component in its own component, so the child component can modify the value of the parent component in the method of the parent component by calling the method of the parent component

// parent component
import React, {Component} from 'react'
import Child from './Child'
class Parent extends Component{   
    // initialization
    constructor(props){
        super(props)
        this.state = {
            message: 'I passed it from the parent component'
        }
    } 
    
    handleUpdate = () =>{
        this.setState({
            message: 'The child component modifies the value of the parent component'
        })
    }
    // render
    render(){
        return(
            <div>
                <Son msg={this.state.message} event={this.handleUpdate()}/>
            </div>
        )
    }
}
export default Parent


// Subassembly
import React, {Component} from 'react'
class Child extends Component{  
    // initialization
    constructor(props){
        super(props)
    }
    // render
    render(){
        return(
            <div>
               {this.props.message}
                <button onClick={() =>{this.props.event()}}>The child component calls the method of the parent component</button>
            </div>
        )
    }
}
export default Child

8. What is JSX? Conversion process from JSX code to display content

JSX is the extended language of JS (jsx syntax = js syntax + xml (html) syntax)

It is a syntax extension of JS and is essentially a JS object. JSX can describe UI information very well, but browsers cannot read it directly, and JSX will be converted into JS syntax during compilation.

render(){
    return(        
        <div>
            <h1> Hello World from Edureka!!</h1>
        </div>
    );
}

9. Advantages and disadvantages of react

advantage:

  • Improved application performance and development productivity
  • Using JSX, the code is more readable
  • React's componentWillUnmount life cycle can clear all related events and avoid memory leaks
  • It does not directly operate on the DOM, and introduces the concept of a virtual DOM, which is inserted between js and the real DOM, with good performance and fast speed 

shortcoming:

Every time  state there is a change, render the function will generate a complete virtual DOM. Even if  state the change is small, renderthe function will calculate it completely. If  render the function is complex, this process wastes a lot of computing resources

Disadvantages of react

10. The difference between the two frameworks of VUE and React 

Similarities:

  • js library for creating UI
  • Quick and easy to use
  • Both use virtual DOM
  • component-based architecture 

difference :

  • The html template used by vue; js is used by react
  • Vue has two-way binding syntax
  • Vue adds grammatical sugar computed and watch, etc. React needs to write its own logic to achieve
  • react uses jsx syntax
  • The overall idea of ​​react is programming, componentization is recommended, data is unchanged, and one-way data flow; Vue data is variable, two-way binding, and declarative writing

React uses js 

11. How React works  

React creates a virtual DOM. When a component's state changes, React first uses the "diffing" algorithm to mark the change in the virtual DOM, and the second step is reconciliation, which updates the DOM with the result of the diff.

12. Prevent React’s default behavior  

e.preventDefault(), e is a synthetic event provided by a third party (note: return cannot be used)

class App extends React.component{
constructor(props){
super(props);
this.state = {
}
}

hands {
e.preventDefault()
}
render(){
return <button onClick={ this.hander.bind(this) }>Block case</button>
}
}

13. Pass parameters to event handlers 

For example to delete the ID of the current row

<button onClick={(e) => this.delete(e,id)}>Delete Row<button>
<button onClick={this.delete.bind(this,id)}>Delete Row</button>

14. What is the role of key in React? 

Mainly used for identification of elements in the list being modified, deleted or added. In the diff algorithm, the key is used to determine whether the element node is deleted or created to reduce unnecessary repeated rendering of elements.

15. The diff algorithm in React 

Function: used to calculate the changed part in VirtualDOM, and perform native DOM operations on this part without re-rendering the entire page

In-depth understanding of React virtual DOM - 110255 - 博客园

16. props and state

  • state is a data structure that can only be changed using setState
  • props is the attribute of the component, which is passed from the parent component to the child component, and props cannot be changed 

The state is local and cannot be accessed by other components except the one where it resides

  • Stateless components: Components that do not have a state set (stateless components are built through functional declarations, and a function is a component)
  • Stateful components: components with state set (stateful components are built through component, and a subclass is a component)

17. React can declare components in two ways, what is the difference between them, and which one would you choose under what circumstances?

  • Function component: the first letter is capitalized, and the react element needs to be returned
  • Class components: the first letter is capitalized, the render method needs to be used, and the react element is returned

the difference:

  • Functional components are the idea of ​​stateless components
  • State cannot be used in function components, and the life cycle method of components cannot be used, which determines that function components are all expandable components, receiving props, rendering DOM, and not paying attention to other logic
  • There is no this in the function component
  • Functional components are easier to understand. When you see a function component, you know that its function is just to receive attributes, render the page, it does not perform logic processing that has nothing to do with the UI, it is just a pure function
// function component
function Welcome(props){
return (
<h1>hello world</h1>
)
}


// Class components: The addition of es6 allows js to directly support the use of classes to define classes. The way react creates components is to use inheritance. The official website recommends this
// How to use, use es6 standard syntax to build
import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component{
        render(){
            return (
            <div>Welcome to the react component</div>
        )
    }
}
ReactDOM.render(
    <App />,document.getElementById('root')
)

18. What are the phases of React component life cycle?

  1. Initial rendering phase: Components will begin their life journey and enter the DOM phase
  2. Update phase: Once a component is added to the DOM, it can only be updated and re-rendered when props or state changes
  3. Unload phase: the last phase of the component life cycle, the component is destroyed and removed from the DOM
  • constructor: initialize props and state in the constructor
  • componentWillMount: Executed before the component renders, and makes the last modification to the state
  • render: rendering
  • componentDidMount: executed after the component is rendered
  • componentWillReceiveProps:This periodic function acts on state transitions caused by specific prop changes
  • shouldComponentUpdate:It is used for performance optimization and returns true or false according to certain conditions. If you want the component to be updated, return true  otherwise return  false . By default it returns false.
  • componentWillUpdate:Data is executed before changing
  • componentDidUpdate:Called immediately after rendering occurs
  • componentWillUnmount:Called after the component has been unmounted from the DOM. Used to clean up memory space

class Timer extends React.Component {
    constructor(props) {
        super(props)
        this.state = {seconds: 0}
    }

    tick(){
        this.setState(state =>({
            seconds: state.seconds + 1
        }))
    }

   componentDidMount() {
        this.interval = setInterval(() => this.tick(),1000)
    }
    
    componentWillMount(){
        clearInterval(this.interval);
    }

    render() {
        return (
            <div>    Seconds: {this.state.seconds}  </div>
        )
    }
}

 In react17, the following three life cycles
componentWillMount, componentWillReceiveProps, componentWillUpdate will be deleted

19. What is unidirectional data flow and state promotion

  • One-way data flow: From top to bottom, the parent component flows the state data to the child component, and the child component takes the value through props
  • State promotion: data interaction between components (many subcomponents want to use this state, promote this state to the top, and use it to whom through props)

Example: If two components need to use each other's state, then state promotion can be used at this time. The specific method is to write the state of the two sub-components into their parent components, and then the parent component passes the state to the props of the sub-components, so that the sub-components are also stateful.

parent component

import React from "react"
import Child1 from "./child1"
import Child2 from "./child2"

export default class Parent extends React.Component {

    constructor() {
        super()
        this.state = {
            money: 1
        }
    }

    changeHander(e){
        this.setState({
            money: e.target.value
        })
    }
    render() {
        return (
            <div>
                <input type="text" value={ this.state.money } onChange={this.changeHander.bind(this)} />
                <p>Parent</p>
                People Ratio: <Child1 money={this.state.money} />
                美金: <Child2 money={this.state.money} />
            </div>
        )
    }
}

 Subcomponent 1

import React from "react"

export default class Child1 extends React.Component{

    constructor(){
        super()
        this.state = {
            input1: 0
        }
    }

    componentDidMount(){
        this.setState({
            input1: this.props.money
        })
    }

    changeHander(e) {
        this.setState({
             input1: e.target.value
        })
    }

    render() {
        return(
            <div>
                 { this.props.money }
               <input type="text" value={ this.state.input1 } onChange={ this.changeHander.bind(this) }/>
            </div>
        )
    }
}

 Subcomponent 2

import React from "react"

export default class Child2 extends React.Component{

    constructor(){
        super();
        this.state = {
            input2: 1
        }
    }

    componentDidMount(){
        this.setState({
            input2: this.props.money * 7
        })
    }

    changeHander(e) {
        this.setState({
             input2: e.target.value
        })
    }
    render() {
        return(
            <div>
                { this.props.money * 7}
               <input type="text" value={ this.state.input2 } onChange={ this.changeHander.bind(this) }/>
            </div>
        )
    }
}

20. What happens after calling setState

setState will update the state

Merge the incoming parameter object with the current state of the component, and then trigger the so-called reconciliation process. After the reconciliation process, according to the new state, the React element will rebuild the virtual DOM, perform a diff algorithm to compare the difference between the old and new virtual DOM trees, and update the view , instead of rendering all

The task queue mechanism adopted by setState will not be executed immediately, but will be added to the queue, and will be executed once in the next event cycle

21. Why is it recommended that the parameter passed to setState be a callback (callback function) instead of an object

updates to this.props and this.state may be asynchronous, and their values ​​cannot be relied upon to calculate the next state

22. About this binding == component binding click event

// bind
// 1
<button onClick={this.handleClick.bind(this)}>hello<button/>
// 2
clicked(param,event){
    console.log(param) //hello world
    console.log(event.target.value) //button
}
render(){
    return (
        <React.Fragment>
            <button value="按钮" onClick={this.clicked.bind(this,"hello world")}>点击</button>
        </React.Fragment>
    )
}


// 2. Bind this by default in the constructor (recommended)
this.handleClick = this.handleClick.bind(this)

// 3. Use the arrow function to handle, the method of handleClick click event
<button onClick={(e) => this.handleClick(e)}>Click me</button>

23. The role of the second parameter of setState 

This function will be called when the setState function call is completed and the component starts to re-render. We can use this function to monitor whether the rendering is complete

24. What is the purpose of calling super(props) (in the constructor)

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

25. What is React routing?

Router is used to define multiple routes, when a user defines a specific URL, if this URL matches the path of any "routes" defined within Router, the user will be redirected to that specific route.

Routing is to display different content or pages according to different url addresses

import React from 'react';
import { Switch, Route, BrowserRouter } from 'react-router-dom';
import Home from './views/Home'

export default class App extends React.Component{
    // initialization
    constructor(props){
        super(props);
        this.state = {}
    }
    // render
    render(){
        return(
           <BrowserRouter>
               <Switch>
                   <Route component={Home} path="/" />
               </Switch>
           </BrowserRouter>
        )
    }
}

26. Distinguish between Real DOM and Virtual DOM

Real DOM Virtual DOM
1. Slow updates 1. Update faster
2. HTML can be updated directly 2. Cannot update HTML directly
3. If the element is updated, create a new DOM 3. Update the JSX if the element is updated
4. DOM operations are expensive 4. DOM operation is very simple
5. Consumes more memory 5. Very little memory consumption

27. Why can't browsers read JSX? 

Browsers can only handle JS objects, not regular JSX. In order for the browser to read JSX, first, a JSX converter like Babel is needed to convert JSX into a JS object, and then pass it to the browser

28. Do you understand the phrase "In React, everything is a component".

Components are the building blocks of a React app's UI. These components divide the entire UI into small independent and reusable parts. Each component is independent of each other without affecting the rest of the UI

29. Explain the purpose of render() in React.

Receive data and return displayed content

class HelloMessage extends React.Component {
  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}

ReactDOM.render(
  <HelloMessage name="Taylor" />,
  document.getElementById('hello-example')
);

30. What are props?

Read-only components must remain pure functions, that is, immutable. They are always passed from parent to child components throughout the application. Child components can never send props back to parent components. This helps maintain a unidirectional data flow and is often used to render dynamically generated data

31. What is state in React? How is it used? 

It is the core of React components, the source of data, and must be as simple as possible. Basically state is an object that determines the rendering and behavior of a component. Unlike props, they are mutable and create dynamic and interactive components. They can be accessed via this.state().

32. Distinguish between state and props

condition State Props
1. Receive the initial value from the parent component Y Y
2. The parent component can change the value N Y
3. Set the default value in the component Y Y
4. Changes within the component Y N
5. Set the initial value of the subcomponent Y Y
6. Change inside the child component N Y

33. How to update the state of the component? 

  • The state of the component can be  this.setState()updated with .
  • replaceState can also be changed 
class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (              
				<div>
                	<h1>Hello {this.state.name}</h1>
					<h2>Your Id is {this.state.id}</h2>
                </div>
            );
        }
    }
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')
);



 class App extends React.Component{

     constructor(props);
      this.state={
      count:1
          title:'Digital Calculation'
      }
}

handleClick=()=>{
  this.replaceState({
    count:this.state.count+1
  })
}

render(){
    return(
      <button onClick={this.onClick}>点我</button>
      )
  }
}

count:1

34. What is an arrow function in React? how to use?

Short syntax for writing function expressions. These functions allow the component's context to be properly bound, since automatic binding is not available by default in ES6. Arrow functions are very useful when working with higher order functions

//General way
render() {    
    return(
        <MyInput onChange = {this.handleChange.bind(this) } />
    );
}
//With Arrow Function
render() {  
    return(
        <MyInput onChange = { (e)=>this.handleOnChange(e) } />
    );
}

35. Distinguish between stateful and stateless components. 

stateful components stateless components
1. Store information about component state changes in memory 1. Calculate the internal state of the component
2. The right to change state 2. No right to change state
3. Include past, present, and possible future state changes 3. Does not include past, present and future possible state changes
4. Accept notifications of state-changing requirements for stateless components, and send props to them. 4. Receive props from stateful components and treat them as callback functions.

40. What are events in React?

 In React, events are triggered reactions to specific actions such as mouse hover, mouse click, key press, etc. Handling these events is similar to handling events on DOM elements. But there are some syntax differences like:

  1. Use camelCase for event names instead of lowercase only
  2. Events are passed as functions instead of strings

Event parameters contain a set of event-specific properties. Each event type contains its own properties and behavior, which are only accessible through its event handlers.

41. What are synthetic events in React?

Acts as a cross-browser object around browser-native events. Merge the behavior of different browsers into one API. This is done to ensure that events display consistent properties across browsers

42. How to create refs? 
import React from 'react'
class test extends React.Component{
    state = {
        myTest: 'jjj'
    }
    testRef = React.createRef() // creates an object
    render(){
    
        return(
            <div>
                <input ref={this.testRef}/>
                <button onClick={() =>{
                console.log("Get the value in the input box", this.testRefs.current.value)
                console.log(this.testRefs.current, 'is an object, DOM can be obtained')
                }}>Click me</button>
            </div>
            )
    }
}
export default test
43. List some situations where Refs should be used.

Get DOM element by ref

  • When you need to manage focus, select text or media playback (see React-60)
  • trigger animation
  • Integrate with third-party DOM libraries
//Set ref in the label, the value is a string
<input type="text" ref="name"/>

//Get the value in the DOM through ref in the function
getInputValue(){
    cnosole.log(this.refs.name.value) //Print out the content entered in the input
}


class ReferenceDemo extends React.Component{
     display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }
render() {
    return(        
          <div>
            Name: <input type="text" ref={input => this.inputDemo = input} />
            <button name="Click" onClick={this.display}>Click</button>            
            <h2>Hello <span id="disp"></span> !!!</h2>
          </div>
    );
   }
 }

43. How to modularize code in React?

Code can be modularized using the export and import attributes. They help to write components separately in different files.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(           
              <div>
              	<h1>This is a child component</h1>
              </div>
        );
    }
}
 
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {    
    render() {        
        return(           
             <div>               
                <App />          
             </div>       
        );  
    }
}

44. Explain the purpose of render() in react

Every React component is mandatory to have a render(). It returns a React element, which is a representation of the native DOM component. If multiple HTML elements need to be rendered, they must be grouped within an enclosing tag, such as <form>, <group>, <div>, etc. This function must be pure, i.e. must return the same result each time it is called.

45. How to embed two or more components into one component?

// can be done in the following way
class MyComponent extends React.Component{
    render(){
        return(          
			<div>
            	<h1>Hello</h1>
                <Header/>
            </div>
        );
    }
}
class Header extends React.Component{
    render(){
        return
			<h1>Header Component</h1>   
   };
}
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')
);

46. ​​React event mechanism 

<div onClick={this.handleClick.bind(this)}>点我</div>

React does not bind the click event to the real DOM of the div, but listens to all events at the document. When the event occurs and bubbles to the document, React encapsulates the event content and hands it over to the real processing function run. This method not only reduces memory consumption, but also uniformly subscribes and removes events when the component is pending destruction.

In addition, the events that bubble up to the document are not native browser events, but synthetic events implemented by react itself. .So if you don't want event bubbling, you should call the event.preventDefault() method instead of calling the event.stopProppagation() method.

How is less memory consumption? ? ?

render component 

 when react element

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>
}

const element = <Welcome name="Sara" />
ReactDOM.render(
    element,
    document.geteElementById('root')
)

47. Event handling

// traditional
<button οnclick="activateLasers()">Active Lasers</button>
// react
<button onClick={activateLaser}>
    Activate Lasers
</button>

// switch button
class Toggle extends React.Component{
    constructor(props){
        super(props)
        this.state = {isToggleOn: true}
        
        // In order to use this in the callback, this binding is essential
        this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
        this.setState(state =>({
            isToggleOn: !state.isToggleOn
        }))
    }

    render() {
        return (<button onClick={this.handleClick}>
                    {this.state.isToggleOn ? 'ON' : 'OFF'
                </button>)
    }
}

ReactDOM.render(
    <Toggle />,
    document.getElementById('root')
)


class LoggingButton extends React.Component{
    handleClick = () =>{
        console.log(this)
    }
    render(){
        <button onClick={this.handleClick}>
            Click me
        </button>
    }

}

48. Controlled and uncontrolled components

Controlled component: control the input value and update in the form of setState

Uncontrolled component: update the value in the form of dom, get the value in the form of ref

// controlled
class NameForm extends React.Component{
    constructor(props){
        super(props)
        this.state = {value: ''}
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
    }


    handleChange(event){
        this.setState({}value: event.target.value)
    }
    
    handleSubmit(event){
        alert('Submitted name:' + this.state.value)
        event.preventDefault()
    }

    render(){
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    name:
                    <input type="text" value={this.state.value} onChange={this.handleChange}/>
                </label>
                    <input type="submit" value="提交"/>
            </form>
        )
    }
}

// uncontrolled
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Demo1 extends Component {
    render() {
        return (
            <input />
        )
    }
}

ReactDOM.render(<Demo1/>, document.getElementById('content'))
 In this simplest input box component, we did not interfere with the value display in the input, that is, the content entered by the user will be displayed on it. If we set an initial default value for the component through props, the defaultValue attribute is an attribute implemented inside React, and its purpose is similar to the placeholder attribute of input.

49. Why create a subdirectory in src?

webpack only handles files in src. If you don't put css and html in the src folder, webpack can't find it.

50. react is a single page application

A single page does not need to load the entire page, a single page is a page, use routing to switch component display, the page has only one index.html, no matter what components are in this page, they are all placed here in the end

Not a single page: It turns out that every click on a link on that kind of website refreshes the entire page, and some logins are refreshed. It turns out that the website will have many html files

advantage:

1. Good interactive experience
  The content change of a single-page application does not need to reload the entire page, and the data is obtained asynchronously through Ajax. Without switching between pages, there will be no "white screen phenomenon" and no suspended animation And with the "flicker" phenomenon, pages display smoothly, and web applications are more responsive and engaging.

2. Good front-end and back-end work separation mode.
  The back-end is no longer responsible for template rendering and output page work. The back-end API is generalized, that is, the same set of back-end program codes can be used for web interfaces, mobile phones, tablets, etc. without modification. client.

3. Reduce the pressure on the server
  Compared with the server, the single-page application has less pressure. The server only needs to output data, regardless of the display logic and page synthesis, and the throughput will increase several times.

shortcoming:

  • The first screen loads slowly

solution:

  • Vue-router lazy loading: The faster the loading speed of the first screen is, the more obvious it is.
  • Accelerate with CDN

Pros and Cons of Single Page Applications

How does React write single-page applications elegantly? - Know almost

Using React to Realize Mobile Single Page Application - Yiyang - 博客园

Implementation of a simple single page

https://blog.csdn.net/u013558749/article/details/68068519?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

52. React-router single-page application--routing management; routing and components; redirection; routing life cycle; lazy loading   

53. What will happen if return () is not used in the render function?

When render returns, there is no need to add parentheses to the content of a single line, but it is necessary to add parentheses to the content of multiple lines

After JSX is converted to js, ​​js will be automatically added to each line ';'. If the line is changed after return, it will becomereturn;

54. Can componentWillUpdate directly modify the value of state

  • No, it will cause an infinite loop error
  • Modify the state directly in react, the render function will not re-execute the rendering, you should use the setState method to modify

55. What is the difference between React events and ordinary HTML events? 

  • Event name naming method, native events are all lowercase, and react events use small camelcase
  • Event function processing syntax, native events are strings, react events are functions
  • The react event cannot use return false to prevent the default behavior of the browser, it must be called explicitly preventDefaultto prevent the default behavior

Synthetic event is an event object that react simulates all the capabilities of native DOM events. Its advantages are as follows:

  • Compatible with all browsers, better cross-platform
  • Store events in an array to avoid frequent addition and deletion (garbage collection)
  • Convenient react unified management and transaction mechanism

The execution order of events is that the original event is executed first, and then the synthetic event is executed. The synthetic event will be bubbled and bound to the document, so try to avoid mixing the native event with the synthetic event. If the native event prevents bubbling, the synthetic event may not be executed. , because the composite event needs to bubble up to the document before it will be executed

56. How to do event proxy in React components? What is its principle?

React implements a SyntheticEvent layer (synthetic event layer) based on Virtual DOM. The defined event handler will receive an instance of a synthetic event object, which complies with W3C standards and has the same interface as native browser events, supporting bubbling mechanism, all events are automatically bound to the outermost layer.

At the bottom of React, it mainly does synthetic events: event delegation and automatic binding.

  • Event delegation:  React will bind all events to the outermost layer of the structure, using a unified event listener, which maintains a mapping to save the internal event listening and processing functions of all components.
  • Automatic binding:  In a React component, the context of each method will point to the instance of the component, that is, this is automatically bound to the current component.

57. Conditional rendering 

Scenario: whether the back button is displayed

import React,{component} from 'react'
export default class App extends Component{
    state = {
        list:[
            {
                id: 1,
                isShow: false
            },
             {
                id: 2,
                isShow: true
            }
        ]
    }
    render(){
        return(
            <div>
                    <ul>
                        {this.state.list.map(item =>{
                            <li key={item.id}>
                                {item.isShow}
                            {item.isShow && <button>返回</button>}
                            </li>
                        })}
                    </ul>
            </div>
        )
    }
}
import React,{Component} from 'react'
class User extends Component{
    render(){
        return(<div>Weclome back!</div>)
    }
}

class Guest extends Component{
     render(){
        return(<div>Weclome back!</div>)
     }
}
export default class App extends Component{
     state = {
        isLogin: false
     }
     render(){
        const isLogin = this.state
        let button
        if(isLogin){
               button = <User /> 
        }else{
                button = <Guest />
        }
        return(<div>
            {button}
        </div>)
     }
}
58. Imitating the v-model instruction in vue, react implements a similar two-way binding

Listen to the value of the input through the onChange event, and display it after changing this.setState 

59. The difference between react stateless components and class components 

  • A function component is a function that returns a react element, which embodies the idea of ​​a stateless component. There is no this, no state, and no life cycle in a function component, which determines that the function component is a display component, receives props, and renders dom
  • Function components do not need to consider component state and component lifecycle methods, and there is a lot of room for performance improvement

60. What is a pure function in React

That is, the same input will always result in the same output, without any observable side effects.

let friend = {
    firstName: 'zhang',
    lastName: 'san',
    age: 18
}
// Impure function: will modify the value of the variable friend outside the function
function appendMessage() {
    friend.message = {
        time: '2021',
        info: 'Learning React'
    }
}
// Pure function: returns a new object and does not modify parameters
function appendMessage(friend) {
    let copyFriend = Object.assign({}, friend)
    copyFriend.message = {
        time: '2021',
        info: 'Learning React'
    }
    return copyFriend
}

61. Does shouldComponentUpdate have it by default? 

Yes, each component will have 

62. What are the ways to pass values ​​in React components 

Father to son: props  

Passing from child to parent: By passing a function and passing parameters in the child component introduced by the parent component, the child component triggers this function to change the parameters to complete the data update

Passing values ​​across multi-layer components: done through context api

63. What are the solutions to realize one-click ui style change in React

  • Prepare style files with different theme colors
  • Record the user's choice in the local cache
  • Every time you enter the application, read the cache and judge which style file to load according to the cached information 

64. Dynamically loaded modules for routing 

When webpack packages a react application, it will package the entire application into a js file. When the user visits for the first time, the entire js file will be loaded. When the application scale becomes larger and larger, the amount of data contained in the js file will also increase. , the rendering speed of the first screen of the website will also be slower

Optimization

  • Multi-entry: use webpack's entry to configure multi-entry, and divide the application package into multiple js files. Suitable for multi-page applications.
  • Routing dynamic loading: use the import() method to split the code at a fine-grained level, and separate each routed component from the main bundle.js file.

65. When to use state manager?

  • Users with different identities have different usage methods (such as ordinary users and administrators)
  • The state of a component needs to be shared
  • A state needs to be available anywhere

================ No need to memorize below 

52. What is Higher Order Component 

A higher-order component is a function whose parameter is a component and returns a new component 

React Higher-Order Components

55. What is render hijacking 

Rendering refers to the JSX syntax part of the render function return in the component. Hijacking is the processing of data and other operations before rendering, modifying the rendering of the original component

Ability to control a component's output from another component

In high-level components, combined rendering and conditional rendering are both types of rendering hijacking. Through reverse inheritance, not only the above two points can be achieved, but also the React elements generated by the render function of the original component can be enhanced.

In actual operation, rendering hijacking can be realized by manipulating state and props

 77. How to configure React-Router 

1. Install

npm install react-router-dom --save

npm install react-router-config --save

2. The difference between HashRouter and BrowserRouter

 BrowserRouter:
  The principle is the history API of H5, which is not compatible with IE9 and below, and needs to be supported by the web server. On the web client side, window.location.pathname is parsed by react router

HashRouter:
  The principle is the hash of the URL, which does not need to be supported by the web server, because its only '/' path needs to be supported by the web server, and the #/react/route URL cannot be read by the web server. On the web client side window, location.hash is parsed by react router

3.index.js

 import { HashRouter as Router } from 'react-router-dom'
 
ReactDOM.render(
  <Router>
    <App />
  </Router>,
 
  document.getElementById('root')
);

4.app.js

// import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import { Link } from "react-router-dom"
import { renderRoutes } from "react-router-config"
import routes from "./routes"
 
class App extends Component {
  render() {
    return (
      <div className="App" >
        <Link to="/">Home</Link>
        <Link to="/communication">Communication</Link>
        <Link to="/find">Find</Link>
        <Link to="/about">My</Link>
 
 
 
        <div>
          {renderRoutes(routes)}
        </div>
      </div>
 
    );
  }
 
}
 
export default App;

 5. Create a routes folder index.js

import Home from "../components/home"
import Communication from "../components/communication"
import Find from "../components/find"
import About from "../components/about"
 
const routes = [
    {
        path: "/",
        exact: true,
        component: Home
    },
    {
        path: "/communication",
        component: Communication,
        // routes: [
        //     {
        //         path: '/communication/:id',
        //         component: Course
        //     }
        // ]
 
    },
    {
        path: "/find",
        exact: true,
        component: Find
    },
    {
        path: "/about",
        exact: true,
        component: About
    },
]
 
export default routes

6. Create the corresponding page in the components folder 

React-Router Routing Configuration

Usage and function of high-level components 

What design pattern is used for high-level components in react 

Using the decoration mode, the use of high-level components:

function withWindowWidth(BaseComponent) {
  class DerivedClass extends React.Component {
    state = {
      windowWidth: window.innerWidth,
    }
    onResize = () => {
      this.setState({
        windowWidth: window.innerWidth,
      })
    }
    componentDidMount() {
      window.addEventListener('resize', this.onResize)
    }
    componentWillUnmount() {
      window.removeEventListener('resize', this.onResize);
    }
    render() {
      return <BaseComponent {...this.props} {...this.state}/>
    }
  }
  return DerivedClass;
}
const MyComponent = (props) => {
  return <div>Window width is: {props.windowWidth}</div>
};
export default withWindowWidth(MyComponent);
copy code

 The characteristic of the decoration mode is that it does not need to change the decorated object itself, but only sets a shell interface outside. JavaScript currently has a proposal for a native decorator, and its usage is as follows:

@testable
   class MyTestableClass {
}
What is the difference between userLayouteffect and userEffect in react hooks 

useEffect is executed asynchronously, while useLayoutEffect is executed synchronously.
The execution timing of useEffect is after the browser finishes rendering, and the execution timing of useLayoutEffect is before the browser actually renders the content to the interface, which is equivalent to componentDidMount. 

 Why can't react hooks be called in loops and conditional judgment statements 

This is because React manages Hooks through a singly linked list. In the update phase, every time useState is called, the linked list will execute next and move backward one step. If useState is written in the conditional judgment, assuming that the conditional judgment is not true, and the useState method inside is not executed, all subsequent useState values ​​will be offset, resulting in an exception. 

 The purpose of userCallback in react hook? 

Optimize child component rendering times 

useCallback and useMemo in react hooks 

The parameters received by useMemo and useCallback are the same, the first parameter is the callback, and the second parameter is the data to be relied on

Joint effect : it will be called only when the dependent data changes, which is to play the role of cache. useCallback cache function, useMemo cache return value.

react hooks function component implements shouldcompensUpdate? 

Implemented using userMemo.

The parent component calls the child component. If any state in the parent component changes, the method code in the child component will be re-rendered. Using userMemo can solve the problem of repeated rendering and redundant rendering

 What problems do hooks in react solve? Why are there hooks? 

① Extract state logic from components, which solves the problem that it is difficult to reuse state logic between components;
② Split the interrelated parts of components into smaller functions, which solves the problem of complex components;
③ In non-class In the case of using more React features, it solves the problem of differences between class components and function components. 

82.hooks parent-child pass value

father to son
Declare data with useState in parent component
 const [ data, setData ] = useState(false)

Pass data to child components
<Child data={data} />

Subcomponent receives
export default function (props) {
	const { data } = props
	console.log(data)
}
child's father
Son-to-father can pass values ​​through the event method, which is somewhat similar to father-to-son.
Declare data with useState in parent component
 const [ data, setData ] = useState(false)

Pass the function that updates the data to the child component
<Child setData={setData} />

When the function is triggered in the child component to update the data, it will be directly passed to the parent component
export default function (props) {
	const { setData } = props
	setData(true)
}
If there are multiple levels of data transfer, it can also be transferred sequentially according to this method

// multi-level useContext
const User = () => {
 // Get it directly without callback
 const { user, setUser } = useContext(UserContext);
 return <Avatar user={user} setUser={setUser} />;
};

Used Redux middleware 

83. Introduce redux, what problem does it mainly solve 

Redux is a solution proposed to solve the communication between react components and the state sharing between components. It mainly includes 3 parts, (store + action + reducer).

store: The object used to store the current react state machine (state). After connect, the change of the store will drive the life cycle of react, thereby driving the change of the page state

action : It is used to accept the state change command, which is the only way and entry point to change the state. In general use, call the relevant action method in the current component, and usually put the communication (ajax) function with the backend here

reducer : action processor, used to modify the value of the state in the store and return a new state value

What is the main problem to be solved:

1. Communication between components

After connect, each connect component shares the store, so each component can communicate data through the store. Of course, some specifications of redux must be followed here, such as view -> aciton -> reducer to change the state path

2. Enter the life cycle through object-driven components

For a react component, it can only change its own state to drive its own life cycle, or drive it through props passed in from outside. Through redux, you can drive components to update through the state changed in the store

3. Convenient data management and slicing

Through the management and control of the store, redux can easily realize the management and slicing of the page state. Through the operation of slices, operations such as redo can be easily realized

How to preserve data across page reloads in React? 

This problem is designed to data persistence, and the main implementation methods are as follows:

Redux: Store the data of the page in redux, and get the data in Redux when the page is reloaded;
data.js: Use webpack to build a project, you can create a file, data.js, and save the data in data.js, Obtained after jumping to the page;
sessionStorge: before entering the selection address page, when componentWillUnMount, store the data in sessionStorage, each time you enter the page to judge whether there is a stored value in sessionStorage, if yes, read the rendering data; no, It means that the data is in an initialized state. Return or enter a page other than the selected address, clear the stored sessionStorage, and ensure that the next time you enter is the initialized data history
API: The pushState function of the History API can associate an arbitrary serializable state with the history record, so it can be pushed in the route Save some information of the current page in the state, and when you return to this page next time, you can take out the data before leaving from the state and re-render. react-router directly supports it. This method is suitable for some scenarios that require temporary storage.

How to use sync/await in React?

async/await is a new feature in ES7 standard. If it is a project created using React's official scaffolding, it can be used directly. If you use it in your own webpack configuration project, you may encounter an abnormal error of regeneratorRuntime is not defined. Then we need to introduce babel and configure async/await in babel. You can use babel's transform-async-to-module-method plug-in to convert it into a syntax supported by the browser. Although there is no performance improvement, the code writing experience is better.

84. Performance optimization at the React level 

For class components and functional components, you can think about performance optimization from the following aspects

  • Reduce the number of re-renders

for example:

The React update process is as follows, we can have two optimization angles

1. props/state changes--->render function changes this stage, reducing the number of executions of render

2. Diff the old and new DOM trees ---> Calculate the difference and update it to reduce the content of the difference

class component:

(1)shouldComponentUpdate

When props and state are updated, the render function will be executed,

At this point, we can use the life cycle  shouldComponentUpdate to control whether render needs to be re-executed. When this life cycle is not written, the function that determines whether the render changes inside React will return true, that is, it will be updated every time by default.

state = { count: 0 }   
shouldComponentUpdate(nextProps, nextState){
     if(nextProps.count === this.state.count){
          return false
     }
     return true 
} 
  • reduce rendered nodes 

(2) Reduce the difference

 In the diff algorithm of virtual DOM, in order to improve performance, only each layer is compared, and no cross-layer comparison is performed. When there is a key, the same key will be compared. If there is no key, the content is different and it will be replaced directly. When we increase the data in reverse order When there is no unique key, the same data will be re-rendered every time. A unique id for each element, since the index value changes based on the data traversed.

<ul>
    <li key="1">Spirited Away's hidden world</li>
    <li key="2">My Neighbor Totoro</li>
    <li key="3">Listen</li>
<ul>
 
<ul>
    <li key="1">The wind is blowing</li>    
    <li key="2">Spirited Away's hidden ghost</li>
    <li key="3">My Neighbor Totoro</li>
    <li key="4">Listen</li>
<ul>
  • Reduce the amount of rendering calculations
  • Rational Design Components

High coupling and low cohesion (reduce unnecessary repeated rendering; reduce the scope of influence when repeated rendering)

One of the most time-consuming places in react is reconciliation. If you don’t execute render, you don’t need reconciliation, so you can see the importance of reducing render in the process of performance optimization.

85. What is the difference between  <Link>tags and tags in react-router<a>

The Link component will eventually be rendered as an HTML tag <a>, and its to, query, and hash attributes will be combined and rendered as an href attribute. Although Link is rendered as a hyperlink, the default behavior of the browser is intercepted by scripts in the internal implementation, and then the history.pushState method is called

Link is only responsible for triggering url changes, and Route is only responsible for rendering components according to url

 Avoid unnecessary rendering compared to  <a> labels<Link>

  How to communicate with class components and function components in react project?

communicate with ref

Specific example reference: React class component (parent component) and function component (child component) ref communication_yang423712's blog-CSDN blog_react parent-child component communication ref

 How to use innerHTML in React

Add the dangerouslySetInnerHTML attribute, and the attribute of the incoming object is named _html

function Component(props){
	return <div dangerouslySetInnerHTML={
  
  {_html:'<span>Hello</span>'}}>
	</div>
}

How does redux request middleware handle concurrency 

Use redux-Saga redux-saga is a middleware that manages the asynchronous operation of redux application, which is used to replace redux-thunk. It stores all asynchronous operation logic in one place for centralized processing by creating Sagas, so as to distinguish the synchronous operation in react from the asynchronous operation, so as to facilitate later management and maintenance. How redux-saga handles concurrency:

How to do event proxy in React components 

The principle of React component event proxy 

In-depth understanding of React: event mechanism principle - OneForCheng - 博客园

How does React check and change data 

  • The props component attribute is specially used to connect the communication between parent and child components. The parent component transmits the parent class members, and the child components can use but cannot edit the parent class members.
  • state: responsible for saving and changing the internal state of the group price

Data transfer: In React, when the parent component transfers data to the child component, the child component obtains the value in the props by setting props through the child component, and the data transfer can be completed. The format of the transferred data can be recognized by any js The data structure props is generally only used as a parent component to pass data to child components, do not try to modify your own props

Data change: props cannot be modified by itself, if the properties inside the component change, use state

this.setState({})

React will monitor the props and state values ​​of each component in real time. Once there is a change, it will update the component immediately and re-render the result to the page, state, props

How react-router implements routing switching 

What does the dependency on inside do  importwhen usingwebpacknode_modules

ReactWhat changes have the interior Domundergone after the structural change 

ReactWhen mounting, there are 3 components, textComponent, composeComponent, domComponent, the difference and relationship, how to distinguish the change of data when the Dom structure changes, how to update, how to schedule the update, and how to deal with other tasks if there are other tasks during the update 

How to handle asynchronous requests in Redux 

The design idea of ​​redux 

The process of accessing redux 

The process of binding connect 

Redux solves problems in state management that React itself cannot solve 

In which life cycle are performance problems generally resolved? 

What details can be optimized when writing react 

React's event mechanism (binding an event to a component) 

How to pass values ​​between React child and parent components 

Introduce React high-level components, what is the difference from ordinary components 

There are 10,000 buttons on the page, how to bind events 

What is the index in cyclic binding, why, and how to solve it 

There is an input and a p tag on the page. After changing the input, the p tag will change accordingly. How to deal with it 

Which event to listen to input and when to trigger it 

How does Redux implement attribute transfer, and introduce the principle 

React-Router version number 

What is the difference between Redux state manager and variables mounted to window 

setStateWhat happens after  in React

seetState() will always trigger a repaint, unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are used, but this logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state can avoid unnecessary re-renders. Usually the state is only used to manage the state related to rendering, so as to ensure that the setState changes the state and the state related to rendering. In this way, unnecessary repeated rendering can be avoided. Other states that have nothing to do with rendering can be directly saved in the component in the form of attributes, and can be called and changed when needed without causing rendering. At the same time, it is necessary to avoid unnecessary modification. When the value of state has not changed, try not to use setState. Although shouldComponentUpdate and PureComponent can avoid unnecessary repeated rendering, they still add a layer of shallowEqual calls, resulting in redundant waste.

setStateWhy is the default asynchronous; setStatewhen is it synchronous 

React design ideas 

Common communication methods of react 

  • Parent-child component communication: The parent component can communicate with the child component by passing props to the child component
  • Cross-level component communication: Contextthe design purpose is to share data that is "global" for a component tree, such as the currently authenticated user, theme or preferred language, which is perfect for communicating global data across multiple Contextlayers
  • Non-nested component communication 

father-son communication

  • Father to son --> props
  • Passing from child to parent--->props+callback function 

Cross-level component communication

  • props passed layer by layer (regardless)
  • context passing 

Non-nested component communication (such as sibling components, etc.) 

Mechanism of use: message subscription and publishing

Several ways of react component communication_kabuda. Blog-CSDN blog_react component communication

Several Ways of Component Communication in React - Programmer Sought

The overall workflow of redux 

First, let's look at a few core concepts:

Store: where the data is saved,

  • You can think of it as a container, and the entire application can only have one Store.
  • State: The Store object contains all the data. If you want to get the data at a certain point in time, you need to generate a snapshot of the Store. The collection of data at this point in time is called State.
  • Action: The change of State will lead to the change of View. However, users cannot access State, only View. Therefore, the change of State must be caused by View. Action is a notification sent by View, indicating that the State should change.
  • Action Creator: As many kinds of messages as View wants to send, there will be as many kinds of Actions. It will be very troublesome if you write them all by hand, so we define a function to generate Action, this function is called Action Creator.
  • Reducer: After the Store receives the Action, it must give a new State so that the View will change. This State calculation process is called Reducer. Reducer is a function that takes an Action and the current State as parameters and returns a new State.
  • dispatch: is the only way for View to issue Action.

Then we go through the whole workflow:

  1. First, the user sends an Action (through the View), and the dispatch method is used in the sending method.
  2. Then, the Store automatically calls the Reducer and passes in two parameters: the current State and the received Action, and the Reducer will return the new State
  3. Once the State changes, the Store will call the listening function to update the View.

React data flow 

Which methods trigger React to re-render?

The setState() method is called

Parent component re-renders 

 What does re-render do?

The old and new VNode will be compared, which is what we call the Diff algorithm

Perform a depth-first traversal of the old and new trees, so that each node will have a mark. When traversing in depth, if a node is not traversed, compare the node with the new node tree. If there is a difference, it will be released. into an object

Talk about the pitfalls of React

 When JSX does expression judgment, it needs to be converted to boolean type

If you do not use !!b to force the data type, 0 will be output in the page

render() {
  const b = 0;
  return <div>
    {
      !!b && <div>This is some text</div>
    }
  </div>
}

What is the concept of react (using functional programming for page rendering) 

Why use Hooks? 

Reasons for using hooks

  • Higher-order components lead to complex code hierarchy for reuse
  • Complex life cycle
  • Written as a functional component, a stateless component, because the state is required, it is changed to a class, and the cost is high 

useState (save component state)

const [state,setState] = useState(initialState) 

What are the commonly used hooks? 

useState: A function that saves the internal state of the component, providing setState to change the state of the component (executed only once during initialization)

useEffect: Perform side effect operations in function components, componentDidMount, componentDidUpdate and componentWillUnmount (state cannot be modified internally)

Responsible for real-time monitoring of certain values. If the second optional parameter is empty, it means to do it on the first render.
If it is a side effect that needs to be cleared, a return can be cleared with one click. 【Data request】 

useContext: passing values ​​across components

useReducer: An enhanced version of useState. In some scenarios, useReducer is more suitable than useState, for example, the state logic is complex and contains multiple sub-values, or the next state depends on the previous state, etc.

useCallback: Similar to useEffect, the function is used as the first parameter, and the dependencies of the function are passed in as the second parameter. The callback function is only called when the dependencies of the function change, and a callback function is returned .

useMemo is similar to uesCallback... ...returns a value.

useRef const refContainer = useRef(initialValue);

useRef returns a mutable ref object whose .current property is initialized to the passed parameter (initialValue). The returned ref object persists throughout the lifetime of the component.
Essentially, useRef is like a "box" that can hold a mutable value in its .current property.
You should be familiar with  ref,  the primary way to access the DOM  . If you pass a ref object into a component as <div ref={myRef} /> , React will set the ref object's .current property to the corresponding DOM node no matter how the node changes.
However, useRef () is more useful than the ref attribute. It can <a href="ht tps://知识-问题,有问题,有问题"> conveniently save any variable value, which is similar to how instance fields are used in class .
This is because it creates a plain Javascript object. The only difference between useRef() and self-built {current: ...} object is that useRef will return the same ref object every time it is rendered.
Remember that useRef doesn't notify you when the ref object's content changes. Changing the .current property does not cause the component to re-render. If you want to run some code when React binds or unbinds a DOM node's ref, you need to use a callback ref  to do so.

Why can't the callback function of useEffect use async?

React itself does not support this. The reason is that the effect function should return a destruction function (effect: refers to the cleanup function returned by return). If the first parameter of useEffect is passed to async, the return value becomes Promise, which will cause react to An error is reported when calling the destroy function: function.apply is undefined

The difference between useCallback and useMemo? How are they cached? 

useCallback returns a function, and useMemo returns a value. 

 When is useCallback not applicable? 

Use useCallback to avoid frequent calls, but when a useCallback's dependencies change, this useEffect will be executed.

Poor memoization, functions are regenerated when dependencies change

· If you want a good memory effect (that is, the dependency is []) but you can’t get the latest state

· The function returned by useCallback also has a closure effect, that is, when we use it in other hooks, the function returned by useCallback is also a function generated in that closure environment.

 Is useState synchronous or asynchronous? If it is asynchronous, how to become synchronous?

In what scenario is it asynchronous?

As long as the setState under the control of react is asynchronous:

One is to improve efficiency. Every time the state value is modified, the render will be re-rendered. Combining and updating the state value multiple times can improve performance;

The second is that the update of render will be later. If there are subcomponents in render, the props of the subcomponent depend on the state of the parent component, and props and state cannot be consistent 

How to get the value of the state when asynchronous

1. In the callback function of setState

this.setState({ 
 count: this.state.count + 1}}, 
 ()=>{ console.log(this.state.count)})

2. Get it in componentDidUpdate

componentDidUpdate(){
 console.log(this.state.count)}

is synchronous

After modifying the state through this.setState, the output state is the new value in its next line

In what scenario is it synchronized?

The setState in the Reduce method is updated synchronously.

setTimeout helps setState escape the control of react, so it is synchronous.

① Native js gets dom elements and binds events

<button id="addBtn">Click me +1</button>componentDidMount(){
 const addBtn = document.getElementById('addBtn')
 changeBtn.addEventListener('click',()=>{
 this.setState({ count: this.state.count + 1})
 console.log(this.state.message)
 })}

② Timer setTimeout

<button onClick={ e => this.addOne() }>点我+1</button>addOne(){setTimeout(()=>{ this.setState({ count: this.state.count + 1 })
 console.log(this.state.count ) },0)}

 The code that wants to obtain the latest value synchronously is written into the callback function and processed in this way;

hook principle 

 How to use innerHTML in React

 Add the dangerouslySetInnerHTML attribute, and the attribute of the incoming object is named _html

function Component(props){
    return <div dnagerouslySetInnerHTML={
  
  {_html:'<span>Hello</span>'}}></div>
}

66. Talk about your understanding of the rendering principle of react

[Issue 1386] React from rendering principle to performance optimization (1)

67. Talk about the attributes of Context

68. How to use Context to develop components 

69. Where to catch errors in React?

Baidu Security Verification

[react] Where to catch errors in React? _The blog of "violating users"-CSDN blog_react catches errors

Error Boundary – React

70. What is the use of the constructor of the react component 

Provides a method for data transfer between component trees without manually adding props for each layer of components  

What is the difference between React high-level components, Render props, and hooks, and why do we need to iterate continuously 

20 high-frequency react interview questions (with detailed explanation) - Programmer Growth Guide - CSDN Blog

Analysis of the principle of virtual DOM

React animation effects 

Such high-quality React interview questions (including answers), if you see it, you will earn it! - Know almost

https://www.aliyue.net/11776.html

react component thinking 

Guess you like

Origin blog.csdn.net/weixin_51225684/article/details/130202647