react extension and basic use of hooks

1. setState

Two ways to write setState update state

	(1). setState(stateChange, [callback])------Object-oriented setState
            1.stateChange Change object for state(This object can reflect the change of state)
            2.callback Is an optional callback function, After the status is updated and the interface is updated(render After call)Was called
					
	(2). setState(updater, [callback])------Functional setState
            1.updater For return stateChange Object.
            2.updater Can receive state and props. 
            4.callback Is an optional callback function, After the status is updated and the interface is updated(render After call)Was called.
summary:
		1.Object-oriented setState It's functional setState Abbreviation of(Grammar sugar)
		2.Use principle:
				(1).If the new state does not depend on the original state ===> Use object mode
				(2).If the new state depends on the original state ===> Use function mode
				(3).If necessary setState()Get the latest status data after execution, 
					In the second callback Read from function

2. lazyLoad

lazyLoad of routing component

	//1. Dynamically load the routing component through the lazy function of React and the import() function = = = > the routing component code will be packaged separately
	const Login = lazy(()=>import('@/pages/Login'))
	
	//2. Specify that a user-defined loading interface is displayed before loading the route packaging file through < suspend >
	<Suspense fallback={<h1>loading.....</h1>}>
        <Switch>
            <Route path="/xxx" component={Xxxx}/>
            <Redirect to="/login"/>
        </Switch>
    </Suspense>

3. Hooks

1. What is react hook / hooks?

(1). Hook yes React 16.8.0 New features added in version/New grammar
(2). You can use it in function components state And others React characteristic

2. Three commonly used hooks

(1). State Hook: React.useState()
(2). Effect Hook: React.useEffect()
(3). Ref Hook: React.useRef()

3. State Hook

(1). State Hook Let function components also have state state, And read and write status data
(2). grammar: const [xxx, setXxx] = React.useState(initValue)  
(3). useState()explain:
        parameter: The specified value is cached internally during the first initialization
        Return value: An array of 2 elements, The first is the internal current status value, The second function is to update the status value
(4). setXxx()2 Writing method:
        setXxx(newValue): Parameter is a non function value, Specify the new status value directly, It is used internally to overwrite the original status value
        setXxx(value => newValue): Parameter is a function, Receive the original status value, Returns a new status value, It is used internally to overwrite the original status value

4. Effect Hook

(1). Effect Hook Allows you to perform side effects in function components(Used to simulate the life cycle hook in a class component)
(2). React Side effect operation in:
        hair ajax Request data acquisition
        Set subscription / Start timer
        Manually change real DOM
(3). Syntax and description: 
        useEffect(() => { 
          // Any operation with side effects can be performed here
          return () => { // Execute before component uninstallation
            // Do some finishing work here, such as clearing timer / unsubscribing, etc
          }
        }, [stateValue]) // If [] is specified, the callback function will only be executed after the first render()
    
(4). Can put useEffect Hook Think of it as a combination of the following three functions
        componentDidMount()
        componentDidUpdate()
    	componentWillUnmount() 

5. Ref Hook

(1). Ref Hook Can be stored in function components/Find labels or any other data within the component
(2). grammar: const refContainer = useRef()
(3). effect:Save label object,Function and React.createRef()equally

4. Fragment

use

<Fragment><Fragment>
<></>

effect

You don't have to have a real DOM root tag

5. Context

understand

A communication mode between components, which is often used for communication between [ancestor component] and [descendant component]

use

1) establish Context Container object:
	const XxxContext = React.createContext()  
	
2) When you render subgroups, wrap outside xxxContext.Provider, adopt value Property to pass data to descendant components:
	<xxxContext.Provider value={data}>
		Subcomponents
    </xxxContext.Provider>
    
3) Data read by descendant components:

	//The first method: only applicable to class components 
	  static contextType = xxxContext  // Claim receive context
	  this.context // Read value data in context
	  
	//The second way: both function components and class components can be used
	  <xxxContext.Consumer>
	    {
	      value => ( // Value is the value data in the context
	        What to display
	      )
	    }
	  </xxxContext.Consumer>

be careful

Generally not used in application development context, Usually use its package react plug-in unit

6. Component optimization

Two problems of Component

  1. As long as setState() is executed, even if the state data is not changed, the component will re render() = = > which is inefficient

  2. Re render() only the current component will automatically re render the child components, even if the child components do not use any data of the parent component = = > low efficiency

Efficient practices

Re render() only when the state or props data of the component changes

reason

shouldComponentUpdate() in Component always returns true

solve

Method 1: 
	rewrite shouldComponentUpdate()method
	Compare old and new state or props data, Return only if there is a change true, If no return false
 Method 2:  
	use PureComponent
	PureComponent Rewritten shouldComponentUpdate(), only state or props Return only when the data changes true
	be careful: 
		Just carry out state and props Shallow comparison of data, If only the internal data of the data object changes, return false  
		Do not modify directly state data, But to generate new data
 Generally used in the project PureComponent To optimize

React.memo

In order to solve the optimization problem in function components, React.memo is added to React in version 16.6. Official website documents: reactjs.org/docs/react-...

React.memo is a high-level component, similar to React.PureComponent, but used for function components rather than class components. If your function component renders the same results under the same props, you can wrap it in react.memo to optimize performance by caching the rendering results. This means that react skips component rendering and uses the last rendered result.

const MyComponent = React.memo(function MyComponent(props) {
  /* render using props */
});
Copy code

React.memo only compares props by default. If you need to customize the comparison, you can pass in the custom comparison function to the second parameter

function MyComponent(props) {
  /* render using props */
}
function areEqual(prevProps, nextProps) {
  /*
  return true if passing nextProps to render would return
  the same result as passing prevProps to render,
  otherwise return false
  */
}
export default React.memo(MyComponent, areEqual);
Copy code

Unlike shouldComponentUpdate in the class component, if props are the same, it should return true, otherwise it should return false. The two are just the opposite.

7. render props

How to dynamically transfer a structure (label) with content into a component?

Vue in: 
	use slot technology, That is, the structure is passed in through the component label body  <A><B/></A>
React in:
	use children props: Pass in structure through component label body
	use render props: Pass in structure through component label properties,And can carry data, generally render Function properties

children props

<A>
  <B>xxxx</B>
</A>
{this.props.children}
problem: If B Component needs A Data in components, ==> can't meet the requirements 

render props

<A render={(data) => <C data={data}></C>}></A>
A assembly: {this.props.render(inside state data)}
C assembly: read A Component incoming data display {this.props.data} 

8. Error boundary

understand:

Error boundary: it is used to capture the errors of descendant components and render standby pages

characteristic:

It can only capture the errors generated by the life cycle of descendant components, not the errors generated by its own components and the errors generated by other components in synthetic events and timers

Usage:

getDerivedStateFromError with componentDidCatch

// The lifecycle function will be triggered once the background component reports an error
static getDerivedStateFromError(error) {
    console.log(error);
    // Triggered before render
    // Return to new state
    return {
        hasError: true,
    };
}

componentDidCatch(error, info) {
    // Error in Statistics page. Send request to the background
    console.log(error, info);
}

9. Summary of component communication mode

Relationship between components:

  • Parent child component
  • Sibling component (non nested component)
  • Grandparent component (cross level component)

Several communication modes:

	1.props: 
		(1).children props
		(2).render props
	2.Message subscription-release:
		pubs-sub,event wait
	3.Centralized management:
		redux,dva wait
	4.conText:
		producer-Consumer model

Better Collocation:

	Parent child components: props
	Brother component: message subscription-Publishing, centralized management
	Grandson assembly(Cross level components): Message subscription-Publishing, centralized management conText(Use less for development and more for packaging plug-ins)

Tags: Javascript node.js Front-end React

Posted by rckehoe on Fri, 24 Sep 2021 18:25:35 +0530