text: 1. The difference between Vue and React
  Everyone has different opinions and answers according to their own understanding.
  2. The difference between class component and function component
  Function component / stateless component
  <script type="text/babel"> // The function name uses the big hump naming specification function MyCom(){ return ( <div> <h1>I am a teacher react Stateless component</h1> </div> ) } ReactDOM.render(<MyCom/>,document.getElementById("demodiv")) </script>
  class component
  A component class must implement a render method. This method must return a jsx element. All the contents must be wrapped with an outer jsx element, and the multiple elements returned in parallel need to be wrapped with a parent element
  <script type="text/babel"> class MyCom extends React.Component{ render(){ return ( <div> <h1>I am a teacher react Class component</h1> </div> ) } } class Fu extends React.Component{ render(){ return ( <div> <MyCom/> <MyCom/> <MyCom/> </div> ) } } ReactDOM.render(<Fu/>,document.getElementById("demodiv")) </script>
  3. Function component implementation life cycle
  - Hook is a new feature of React 16.8. It allows you to use state and other React features without writing a class.
  - Use effect in Hook. By using this Hook, you can tell the React component that it needs to perform some operations after rendering. useEffect needs a set of dependent states. If the dependent state changes, the callback will be executed
  4. The role of refs in react
  - We need to grab DOM elements, integrate with the third-party DOM library, trigger command animation, manage focus, select text or play media
  - A reference to a real instance of a component (that is, an html tag, that is, a DOM object) is ReactDOM.render() returned component instance; ref can be written in html tag or component (custom tag), which has the same meaning as ref in vue.
  - Official advice: do not overuse Refs (try not to operate DOM), and give priority to state (data-driven) when processing logic.
  5. refs forwarding in react
  6. Context state tree
  In the normal process of using react, the data is transferred from top to bottom. For example, if the data related to theme is stored in the state of the top-level component, it will be managed as the theme of the whole App. Then, without the help of any third-party state management framework, if you want to obtain the theme data in the subcomponents, you must pass it layer by layer, even if the components between them do not need the data at all.
  Context is designed to share a component tree, which can be regarded as "global" data to achieve leapfrog transmission. Scenario: the current authenticated user, theme or preferred language, including managing the current locale, theme, or some cached data.
  createContext(): used to create a context. It needs a parameter of default value and returns an object containing Provider and Consumer
  Provider: provider, providing data. Receive a props that will be passed down layer by layer. The value needs to be set at the top of the component tree. A provider can be associated with multiple Consumers. This is a top-level component used to provide context. It contains a props of value. Value is the actual context data.
  Consumer: the consumer receives a function as a child node, and the function receives the value of the current context. This is a low-level component used to obtain context. It needs a function as its child element. The function contains a value parameter, and the parameter of the function is the context value passed by the upper layer
  Create a context component and set the default value. The syntax is as follows:
  const {Provider, Consumer} = React.createContext(defaultValue);
  Example code:
  context assembly: ./src/utils/myContext; import {createContext} from "react"; export const {Provider, Consumer} = createContext({ name:"Zhang Sanfeng" }); //Top level component:. / src/App.js import {Provider} from "./utils/myContext" function App() { let val={ name:"hi" }; return ( <div className="App"> <Provider value={val}> <Home /> </Provider> </div> ); } //Sunzi component: app > Home > goodlist import {Consumer} from "../utils/myContext"; export default class GoodsList extends React.Component { render = () => ( <div className="goodsList-box"> <h1>Product list:</h1> <Consumer> { (val) => <div> { val.name } </div> } </Consumer> </div> ) }
  be careful:
  export const {Provider, Consumer} = createContext({
  name: "Zhang Sanfeng"
  });
  The default value is when the top-level component does not use the Provider component, not when the value attribute is not assigned.
  That is, the code of the top-level component is as follows:
  function App() { let val={ name:"hi" }; return ( <div className="App"> <Home /> </div> ); }
  7. Prototype, prototype chain and inheritance
  - Prototype: each constructor has a prototype attribute, which will become the prototype object of the instance object when the instance is generated. Each object of javascript inherits another object, which is called a "prototype" object.
  - Prototype chain: each object has one__ proto__ Properties, the properties and methods of an object, may be defined in itself or in its prototype object. Since the prototype itself is also an object and has its own prototype, it forms a prototype chain. (the function of "prototype chain" is: when reading an attribute of an object, the JavaScript engine first looks for the attribute of the object itself. If it can't find it, it goes to its prototype. If it still can't find it, it goes to its prototype. If you go to the top Object.prototype If it is still not found, undefined is returned. For example, if the prototype property of a function points to an array, it means that the function can be used as the constructor of the array, because the generated instance objects can call the array method through the prototype property.)
  - Inheritance: inheritance is to inherit the private and prototype properties of the parent constructor in the subclass constructor. In the subclass constructor, we use call or apply method to call the parent class constructor and change this to this, which is the subclass constructor. At this time, the subclass constructor inherits the private properties and methods of the parent class. The instantiated object of the parent class is assigned to the prototype object of the subclass, and the subclass inherits the prototype properties and methods of the parent class.
  8. The function of new in JS
  Create an empty object and make it inherit Func.prototype ；
  Execute the constructor and point this to the new object you just created;
  Returns the new object;
  9. Closure
  Official explanation: a closure is an expression (usually a function) that has many variables and an environment bound to them, so these variables are also part of the expression. (a function is an expression)
  In general, all functions in JavaScript are closures. However, in general, nested functions produce more powerful closures, which we call "closures" most of the time.
  What is a closure: a closure is a function that accesses variables (local variables) in the scope of a function outside the function; In other words, a closure is a function that can read the internal variables of other functions; in other words, a closure is a function that has access to the variables in the scope of another function; in Javascript, only the internal sub functions of a function can read local variables, so a closure can be simply understood as "a function defined within a function".
  Application scenarios: Anti shake and throttling,Coritrization of functions
  10. Array de duplication
  - Using ES6 Set to remove duplicate (most commonly used in ES6)
  function unique (arr) { return Array.from(new Set(arr)) } var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr))
  - Use for to nest for, and then split to remove duplicate (most commonly used in ES5)
  function unique(arr){ for(var i=0; i<arr.length; i++){ for(var j=i+1; j<arr.length; j++){ if(arr[i]==arr[j]){ //The first is equivalent to the second, and the splice method removes the second arr.splice(j,1); j--; } } } return arr; } var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr))
  - Using the properties of an object
  function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } var arrry= []; var obj = {}; for (var i = 0; i < arr.length; i++) { if (!obj[arr[i]]) { arrry.push(arr[i]) obj[arr[i]] = 1 } else { obj[arr[i]]++ } } return arrry; } var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr))
  11. The difference between set and map
  The main application scenarios of Set and Map are data reorganization and data storage.
  Set is a data structure called set, and Map is a data structure called dictionary.
  - Common point: set and dictionary can store non duplicate values
  - Difference: set stores elements in the form of [value, value], dictionary stores elements in the form of [key, value]
  set: a new data structure in ES6, which is similar to array, but its members are unique and unordered, with no duplicate values.
  Set itself is a kind of constructor used to generate set data structure.
  The Set object allows you to store unique values of any type, whether they are original values or object references.
  (Dictionary) map: is a set of key value pairs structure, with extremely fast search speed.
  12. Promise, async and await
  - Promise is a solution of asynchronous operation, which expresses the complex traditional callback function and asynchronous operation of listening event in the form of synchronous code. The nested callback function of multi-level asynchronous operation is avoided.
  - 1. It is mainly used for asynchronous computing
  - 2. The asynchronous operations can be queued, executed in the expected order, and the expected results can be returned
  - 3. You can pass and manipulate promise between objects to help us deal with queues
  - Promise is an object. There are actually three states inside it.
  - The initial state (pending).
  - Resolve: the resolve method can change the state of the Promise object to success
  - Reject: the reject method changes the state of the Promise object to fail
  - Three methods of Promise
  - The first type: then indicates that the data state after asynchronous successful execution changes to resolve
  - The second type: catch indicates that the data state of execution after asynchronous failure changes to reject
  - Third: all means to encapsulate multiple unrelated promises into a Promise object and use then to return an array data.
  - The Promise constructor has two variables: resolve is used to return the successful function of asynchronous execution, reject is used to return the failed function of asynchronous execution, which is used together with then and catch
  Promise usage scenarios
  - When Ajax requests asynchronously
  - The advantage of using promise when there are many levels of function nesting is that the callback function has become a chained writing method, the process of the program can be seen clearly, and there is a complete set of supporting methods, which can realize many powerful functions.
  13. ES6 Symbol
  14. Deep and shallow copy
  fifteen width:auto And width:100% The difference between
  width:100% It does not contain the attribute value of margin left margin right. It directly takes the width of its parent container plus the value containing margin left / margin right. If margin is set, the new width value is the width of the container plus the value of margin. (careful observation) you will find that the margin corresponding to the edge will be more blank settings. And there will be more horizontal scrollbars, because the width is beyond the range of the screen. (this is body relative to the parent container).
  width:auto Contains the property value of margin left / margin right. Its value contains the value of margin left / margin right. width:auto Always occupy the whole line!!! The value of margin is already included (that is, a whole line). If you want to set the value of margin, you can use a whole line and subtract the value of margin to get the current width. The minus value is the blank of the corresponding edge. The remarkable feature is that there is no horizontal scroll bar, that is, the width is not increased.
  16. The difference between pseudo elements and pseudo classes
  - Pseudo class: used to add special effects to some selectors
  - Pseudo elements: used to add special effects to some selectors
  17. react hooks
  Introduction to Hooks
  react hooks is a new feature in v16.8, which allows you to operate state and react's other features (such as hook function of life cycle) without writing class (i.e. functional component).
  hooks is just a way to write components, which makes it easier and more convenient to write a component. At the same time, you can customize hook s to extract common logic, so that the logic can be shared among multiple components.
  What is hook? Hook is a special function that allows you to "hook in" React features. For example, useState is a hook that allows you to add a state to the React function component.
  There is no state in a functional component, so we use functions to write stateless components, or functional components are stateless components. Now with Hook, state can also be used in functional components. There are other hooks, of course.
  Rules of use
  - Hook allows you to use state and other React functions without writing classes (components)
  - Hooks can only be called at the top level. Do not call Hook in loops, conditions or nested functions.
  - Hooks can only be used in functional component s or custom hooks
  - Hooks don't work inside the class and there's no plan to remove the class from React
  useState:
  Format:
  1,definition: const [State name, function to update state] = React.useState(Initial value|function); For example: Declare a new one called“ count" Of state Variable with an initial value of 0. const [count, setCount] = useState(0); Equivalent to the this.state={ count :0 } const [person, setPerson] = React.useState({name: 'Zhang Sanfeng', age: 18,sex:"female"}) const [person, setPerson] = React.useState(() => ({name: 'Zhang Sanfeng', age: 18,sex:"female"})) 2,Read value: {count} {person.name} {person.age} 3,Modified value: It can't be updated locally, so you need to use the extension operator to copy all the previous properties first setCount(5); setPerson({ ...person, //All properties before copying age:person.age+1, name: 'Zhang Sifeng' //The name here overlaps the previous name })
  Example code:
  import React,{useState} from 'react'; function App() { // The declaration of a variable is called "count" const [count,setCount] = useState(0); return ( <div className="App"> <p>{count}</p> <input type="button" value="test" onClick={()=>{setCount(count+1)}} /> </div> ); }
  Corresponding function class component:
  class App extends React.Component { state = { count:0 } render = () => ( <div> <p>{this.state.count}</p> <input type="button" value="test" onClick={()=>this.setState({count:this.state.count+1})} /> </div> ) }
  We used to call functional components "stateless components". But now we've introduced the ability to use React state for them
  Another example is:
  function App() { const [person, setPerson] = React.useState({name: 'Zhang Sanfeng', age: 18}) const onClick = () =>{ //setPerson cannot be updated locally. If only one of them is changed, the whole data will be covered. Therefore, you need to use the extension operator to copy all the previous properties first setPerson({ ...person, //All properties before copying age:person.age+1, name: 'Zhang Sifeng' //The name here overlaps the previous name }) } return ( <div className="App"> <p>name:{person.name}</p> <p>age:{person.age}</p> <input type="button" value="test" onClick={onClick} /> </div> ); }
  Use effect to deal with side effects
  It allows you to perform side effects in function components. Oh, my God, side effects.
  Every time the react component is updated, the useEffect will be triggered. It will be triggered after the first render and every update. There is no need to consider "Mount" or "update". React ensures that DOM has been updated every time the effect is run.
  You can think of useEffect Hook as a combination of three functions: componentDidMount, componentDidUpdate and componentWillUnmount.
  We don't have componentDidMount, componentDidUpdate and componentWillUnmount in functional components. We use useEffect. That is: when the data changes, it will be rendered to the component. After the component is rendered, it will call useEffect.
  import React,{useState,useEffect} from 'react'; function App() { const [count,setCount] = useState(0); useEffect(()=>{ console.log("userEffect"); document.title = count; }); return ( <div className="App"> <p>{count}</p> <input type="button" value="test" onClick={()=>{setCount(count+1)}} /> </div> ); }
  useRef saves the reference value
  useRef returns a variable ref object whose. current property is initialized as the parameter (initialValue) passed in. The returned ref object remains unchanged throughout the life cycle of the component.
  import {useRef} from "react"; let refContainer = useRef(initialValue) <JSX ref={refContainer} ... refContainer.current.dom operation
  A common use case is imperative access to subcomponents
  function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current 'refers to the text input element that has been mounted on the DOM inputEl.current.focus(); }; return ( <> <input ref={inputEl} <button onClick={onButtonClick}>Focus the input</button> </> ); }