What is Immutable? Advantages?

Immutable is data that, once created, cannot be changed. Any modification or addition or deletion of an Immutable object returns a new Immutable object.

Immutable data is a persistent data structure that ensures that old data is available at the same time when new data is created. Immutable also uses Structural Sharing to avoid the performance cost of deepCopy copying all nodes at once. If a node in the object tree changes, Immutable modifies only that node and its affected parent, and the other nodes share it.

Example comparison:

// let foo = {a: {b: 1}}; let bar = foo; bar.a.b = 2; console.log(foo.a.b); // Prints 2 console.log(foo === bar); // print true // import immutable from 'immutable' with immutable. foo = Immutable.fromJS({a: {b: 1}}); bar = foo.setIn(['a', 'b'], 2); / / use setIn assignment console. The log (foo getIn ([' a ', 'b'])); // Use getIn to print 1 console.log(foo === bar); / / print falseCopy the code

Advantages:

  1. Immutable reduces the complexity of Mutable

Mutable data couples the concepts of Time and Value, making it difficult to track back. 2. Memory saving: Immutable uses Structure Sharing to reuse memory as much as possible. Objects that are not referenced are garbage collected

import { Map} from 'immutable'; let a = Map({ select: 'users', filter: Map({ name: 'Cam' }) }) let b = a.set('select', 'people'); a === b; // false a.get('filter') === b.get('filter'); // true above a and B share the unchanged 'filter' node.Copy the code
  1. Undo/Redo, Copy/Paste, you can easily create Undo/Redo functions (time travel is a piece of cake)
  2. Concurrency security: Data is inherently immutable, so concurrency locking is not required
  3. Functional programming

Disadvantages:

  1. You need to learn new apis
  2. Increased resource file size
  3. Easy to confuse with native objects

This is the biggest problem we have with Immutable. Writing code requires a mental shift.

Although Immutable tries to be similar to native objects designed by the API, it can sometimes be difficult to tell Immutable from native, confusing operations.

Immutable Map and List correspond to native objects and arrays, but operate very differently, e.g. you use map.get(‘key’) instead of map.key, and array.get(0) instead of Array [0]. In addition, Immutable returns new objects every time it is modified, and it is easy to forget assignments.

When working with external libraries, you generally need to use native objects, and it’s easy to forget about transformations.

Here are some ways to avoid similar problems:

- Use static type checking tools such as Flow or TypeScript - Convention variable naming: all Immutable objects begin with '$$'. - Create objects by using 'Immutable. FromJS' instead of 'Immutable.Map' or 'Immutable.Copy the code

Immutable is distinct from Object. Freeze, const

Object.freeze and the new const additions in ES6 prevent objects from being tampered with, but they are shallowCopy. Once the object level is deep, special processing is required.

What are controlled components and non-controlled components?

  • Controlled components: form elements whose values are controlled by React (<input>, <textarea>, <select>), which also means that the form component can immediately respond to input changes
class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {val: ' '};
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
   // When this line of code is commented and the text box is entered again, the page is not re-rendered. The effect is that the text box cannot enter a value, that is, the change of the text box value is controlled by the setState() method.
    this.setState({ val: event.target.value });
  };
  render() {
    return (
      <div>
          <input type="text" value={this.state.name} onChange={this.handleChange}/>
      </div>); }}Copy the code

Such as other tags: Textarea and onchange Select and onchange

  • Uncontrolled component: Not controlled by setState() and similar to traditional HTML form input, the input value displays the latest value
class Demo extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { console.log(this.input.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={(input) => this.input = input} /> </label> <input type="submit" value="Submit" /> </form> ); }}Copy the code

Characteristics of controlled and uncontrolled components

features uncontrolled controlled
One-time retrieval (for example, form submission) is is
In a timely manner to verify non is
Conditional disable submit button non is
Execute input format non is
Several inputs to one data non is
Dynamic input non is
The form data is handled by the DOM itself is non

What is state promotion

In a nutshell, you promote the state that multiple components need to share to their nearest parent. This state is changed on the parent component and then distributed to the child component via props.

The way it works is that the child changes the data passed by the parent by passing in a method that the child triggers

Usage scenario: Two input fields (belonging to two components) are provided to ensure the synchronization of the contents in the input fields

class Son extends React.Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this) }  handleChange(e) { this.props.onFatherMethod(e.target.value) } render() { return ( <input type='text' value={ this.props.content } onChange={ this.handleChange } /> ) } }Copy the code
class Father extends React.Component {
   ...
    handleContentChange(newContent) {
        this.setState({ content: newContent })
    }
    render() {
        return (
            <div>
            	<Input content={ this.state.content } onFatherMethod={ this.handleContentChange }/>
                <br />
                <Input content={ this.state.content } onFatherMethod={ this.handleContentChange }/>
            </div>
        )
    }
}
Copy the code

What is a stateless component

A stateless component is one in which there is no state

What is HOC? What does it do? Features?

Higher-order function: a function that takes a function as an argument. The map function is a higher-order function

High-order components: Not an API provided by React, but a mode that uses React. This is similar to high-order functions, which take the React component as arguments and output a new component. In this function, we can modify the props and state of the component, so higher-order components can make our code look prettier in certain cases.

Note: The new component returned has functionality that the input component does not. The component mentioned here is not a component instance, but a component class, which can also be a function of a stateless component.

Function:

  • More reusable: ShouldComponentUpdate (shouldComponentUpdate, shouldComponentUpdate, shouldComponentUpdate, shouldComponentUpdate, shouldComponentUpdate, shouldComponentUpdate) You can reduce repetitive code for many components.
  • Modify the behavior of existing React components: Some existing React components are not developed by developers, come from third parties, or even by ourselves, but we don’t want to touch the internal logic of these components. With a function independent of the original component, a new component can be created without any harm to the original component.

At present, there are two main ways to realize higher-order components:

  • High-order components in proxy mode: High-order components operate functions through the wrapped React component
    • In the higher-order component, which can modify props to state, define state in the higher-order component as the props to the InnerComponent.
    • Higher-order components can also pass methods to the InnerComponent
    • The lifecycle of higher-order components does not affect incoming components
    • Not all life cycles of higher-order components are executed first
    • New components generated from the same higher-order component do not affect each other
  • High-order components inherited: High-order components inherit from the wrapped React component
    • Manipulation of the props
    • Manipulation life cycle

Proxy mode instance

const HOC = (InnerComponent) = > class extends React.Component{
    static defaultProps = {
        n:'HOC'
    }
    constructor(){
        super(a);this.state = {
            count:0}}componentWillMount(){
        console.log('HOC will mount')}componentDidMount(){
        console.log('HOC did mount')
    }
    update = () = >{
        const {count} = this.state
        this.setState({
            count:count+1})}render(){
        const newProps = this.state;
        return(
            <InnerComponent
                {. this.props}
                {. newProps} / /state
                update = {this.update}// pass method />)}}// Stateless components
const Button = HOC((props) = > <button onClick={props.update}>{props.children}-{props.count}</button>) // Stateless components

// Changing count in Button does not affect count in Label component
class Label extends React.Component{// Traditional components
    static defaultProps = {
        n:'C'
    }
    componentWillMount(){
        console.log('C will mount')}componentDidMount(){
        console.log('C did mount')}render(){
        return(
            <label>{this.props.children}-{this.props.count}</label>)}}const LabelHoc = HOC(Label)

class App extends React.Component{/ / the root component
    render(){
        return(
            <div>// Render label-0, 1, 2..... with click<Button>button</Button>
                <br/>// Render: label-0<LabelHoc>label</LabelHoc>
            </div>)}}Copy the code

Inheritance mode instance

const HOC = (WrappedComponent) = > 
  class NewComp extends WrappedComponent {
    componentWillMount() {
      console.log('I'm inheriting the lifecycle in a higher-order component.')}render() {
      // Gets the inherited element content of the passed component
      const element = super.render()
      const newStyle = {
        color:element.type === 'div' ? 'red' : 'yellow'
      }
      constnewProps = {... this.props,style: newStyle}
      // the React. CloneElement method generates a new React object
      return React.cloneElement(element, newProps, element.props.children)
  }
}
export defaultHOC The normal component passes in the high-level component @hocclass A extends Component {
  componentWillMount() {
    console.log('I'm the life cycle in a normal component')}render() {
    return (
      <div>I'm a normal component</div>)}}export defaultA Final effect: div is red ———— this is the manipulation props instance output: I am inheriting the lifecycle of the higher-order component (the lifecycle content in A is missing and hijacked by inheriting the higher-order component) ———— this is inheriting the higher-order component manipulation lifecycleCopy the code

What is Context? How do you use Context?

Context provides a way to pass data through the component tree, eliminating the need to manually pass props properties at every level.

React. CreateContext: Creates a container (component) for context. DefaultValue can set the default data to be shared

const {Provider, Consumer} = React.createContext(defaultValue);
Copy the code

Provider: a place to produce shared data. What we produce depends on what value defines. Value: places shared data.

<Provider value={/* share data */}> /Copy the code

Consumer: Specialized Consumer providers (Provider mentioned above) generate data. The Consumer needs to be nested under the producer. To retrieve the shared data source through a callback. Of course, it can also be used alone, so that only the defaultValue mentioned above can be consumed

<Consumer> {value => /* Render content according to context */} </Consumer>Copy the code

Example:

export const {Provider,Consumer} = React.createContext("Default name");

export default class App extends React.Component {
    render() {
        let name ="hannie"
        return (
            // The Provider shared container receives a name attribute
            <Provider value={name}>
                <div style={{border:'1px solid red'}} >
                    <p>Values defined by the parent component :{name}</p>
                    <Son />
                </div>
            </Provider>); }}function Son(props) {
    return (
        // The Consumer container can get the name attribute passed above and display the corresponding value
        <Consumer>
            {( name ) =>
                <div style={{ border: '1px solid blue'}} >
                    <p>The child component. Get the value of the parent component :{name}</p>
                    <Grandson />
               </div>
            }
        </Consumer>
    );
}


function Grandson(props) {
    return (
         // The Consumer container can get the name attribute passed above and display the corresponding value
        <Consumer>
            {(name ) =>
               <div>
                   <p>Sun components. Get the passed value :{name}</p>
               </div>
            }
        </Consumer>
    );
}
Copy the code

What is a pure function

  1. The return result of a function depends only on its arguments
  2. The function is executed without affecting external variables.
let a = 1
let func = (a) = > a+1Fun (a) depends on other arguments Counterexample: Return results also depend on Alet a =1
let func = (b) = > a+b
fun(2)
Copy the code
const counter = {x:1}
let func = (counter) = > (
  counter.x+1
) 
console.log(func(counter))  / / 2Side effect counter examplelet counter = { x:1 }
let func = (counter) = > {
  counter.x=2
  return counter.x+1 
}
console.log(func(counter)) / / 3
console.log(counter.x) //2 is affected by func(counter) execution
Copy the code

Examples of side effects: Ajax requests for back-end data, adding login listeners and cancelling login, manually modifying the DOM, calling window.reload to refresh the browser, and so on all affect external variables

In React, the state of a pure function can only survive the life cycle inside the function

Reducer is a pure function that accepts old state and action and returns newState (previousState, action) => newState

What is React Portal? What are the usage scenarios

Previously, all components in React would be located under #app, but using Portals provides a way for components to exit #app.

Portals are suitable for components that are out of flow, especially position: Absolute and Position: Fixed. Such as modal boxes, notifications, warnings, goTop, etc.

<html>
  <body>
    <div id="app"></div>
    <div id="modal"></div>
  </body>
</html>
Copy the code
const modalRoot = document.getElementById('modal');

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el);
  }

  render() {
    return ReactDOM.createPortal(
      this.props.children,
      this.el, ); }}Copy the code

React16 What is an Error Boundary?

The screen will go blank if an error is reported before the launch, so we always need to do manual try catch at the front end. React16 added two new life cycles componentDidCatch and Static getDerivedStateFromError from the framework level to make it easier to catch exceptions and display alternate UI. This is essentially a try catch around the entire workloop, and when an error is reported, the parent component is iterated to find the two lifecyls and the stack information is inserted into the lifecyls for judgment.

Usage scenario: in the occurrence of JS error will not say white screen, you can turn to another page to remind the user of the error reported here;

Error handling is used when a JS error occurs in a component

What are createElement and cloneElement in React? What’s the difference?

Both createElement and cloneElement can generate tag languages that can be used directly in JSX page components, but there are subtle differences in how they are generated

  • createElement
  1. Type is a tag name. Such as div, SPAN, or React components
  2. Props is the property passed in
  3. The third and subsequent arguments, children, are children of the component
React.createElement(
  type,
  [props],
  [...children]
)
Copy the code
  • cloneElement
  1. The first element passed in is a React element, whileNot tag names or components
  2. Props is the property passed in
  3. The third and subsequent arguments, children, are children of the component
React.cloneElement(
  element,
  [props],
  [...children]
)
Copy the code

Features: The newly added attributes are incorporated into the original attributes and passed into the returned element, while the old child elements are replaced and the keys and references of the original element are retained.

getChildren(){
    const  that = this;
    let { children } = that.props;
    return React.Children.map(children, child= > {
        return React.cloneElement(child, {
            count: that.state.count
        });
    });
}
Copy the code

The createElement function is used by JSX to create a React Element.

CloneElement is used to clone an element and pass in new Props

What is the difference between Elemnet and Component in React?

An Element is a data structure that describes what is seen on the screen and is an object representation of the UI. A typical React Element is a declarative piece of code built with JSX that is then converted into a combination of createElement calls.

The React Component is a function or class that takes parameter input and returns a React Element

What are the props and state in React? What’s the difference

Definition:

  • Props is an external parameter that is used to pass data from the parent component to the child component. It is readable and immutable. Only the external component can actively pass in new props to re-render the child component, otherwise the props and presentation of the child component will not change.

  • State is used by a component to save, control, and modify its state. It can only be initialized by constructor and is considered a private property of the component. It cannot be accessed or modified externally, but can only be modified by using the this.setState property inside the component.

The difference between:

  1. State is the component’s own management of data, control of its own state, variable;

  2. Props is an external data parameter that is immutable.

  3. A stateless component without state is called a stateless component, and a stateless component with state is called a stateful component.

  4. Use props more than state. That is, write more stateless components.

What’s the difference between Presentational component and Container Component in React

  • Containers
  1. Care more about how the component works, interacting with the background, connecting to Redux, calling actions, passing data to the Component

  2. Stateful because they are the data source

  3. For readability, reusability, and maintainability

  • Presentational
  1. The presentation component cares about what the component looks like, responsible for rendering
  2. There is almost no state of its own, but when a presentation component has its own state, it is usually only concerned with the STATE of the UI and not the state of the data.

How to use async/await in useEffect

The useEffect callback argument cannot return a Promise and therefore cannot use async/await, at which point you can choose to wrap another layer of function

async function fetchApi() { let response = await fetch(url) response = await res.json() handleData(response) } useEffect(() => { fetchApi(); } []);Copy the code

How to communicate?

React and Vue communicate with each other

What is the life cycle?

See my other post about the React and Vue life cycles

React hooks

React and Vue hook functions React and Vue hook functions React ‘common hook

How to emulate componentDidMount in React Hooks

In useEffect, set the second parameter, the dependent state, to [].

useEffect(callback, [])
Copy the code

Why can’t you define React hooks in expressions

Because React Hook is based on a linked list implementation, it calls on the condition that all hooks are executed sequentially every time a component is rendered.

If you are using SSR, can access to the localStorage in created/componentWillMount

Can’t, created/componentWillMount, haven’t mount, code execution in the server, still no browser environment at this time, so at this time access to the localStorage, an error will be

What does Fiber do in React

Due to the single-threaded nature of JavaScript, each synchronization task should not take too long, otherwise the application will not respond to other inputs. React Fiber is a change in this situation. Sharding can be used to solve the problem of long synchronization in JavaScript.

A long task is divided into many small pieces, each of which has a short running time. Although the total time is still very long, other tasks are given a chance to execute after each small piece is executed, so that the only thread is not monopolized and other tasks still have a chance to run.

React Fiber fragmented the update process, giving control back to the React mission coordination module at the end of each update process to see if there are other urgent tasks to be done. If there are no urgent tasks to be done, keep updating. If there are urgent tasks to be done, do urgent tasks.

The data structure that maintains each shard is called Fiber.

Reference links:

www.cnblogs.com/qiangxia/p/…

Q.s hanyue. Tech/fe/react / 69…

www.520mg.com/a/inter/rea…