setState()
Simple case:
The case code is as follows:
import React from "react"; //UI components export default class Person extends React.Component{ state = {count:0} increment = () => { const {count} = this.state this.setState({count:count+1}) console.log(this.state.count) // 0 the page displays 1 } render(){ return( <div> <h2>The current summation is:{this.state.count}</h2> <button onClick={this.increment}>Point me+1</button> </div> ) } }
1.setState is written in two forms
- The first is that the first parameter is in the form of object type (often used)
this.setState({count:count+1})
- The second is that the first parameter is in the updater function (there are two parameters state and props)
this.setState((state, props) => { return {counter: state.counter+1}; });
2. What does setstate do
- setState() will schedule an update to the state object of a component. When the state changes, the component will be re rendered.
3. After setstate is updated, the value printed later remains unchanged, but the page value changes?
- setState() itself is a synchronous method, but the action caused by the state update in react is asynchronous. Therefore, the official website said: "calling setState is actually asynchronous - don't expect this.state to be mapped to a new value immediately after calling setState."
- Treat setState() as a request rather than a command to update components immediately. For better perceptual performance, react will delay calling it, and then update multiple components through one delivery. React does not guarantee that changes to state will take effect immediately.
4. How to get the latest value immediately after setstate is updated?
- Object type setState update: the setState function can pass in the second parameter (callback function). This callback function gets the count value after the page is re render ed, so you can go to the latest value after the change is completed in the callback function
increment = () => { const {count} = this.state this.setState({count:count+1},()=>{ console.log(this.state.count) // 1 is the same as the value displayed on the page }) }
- The componentDidUpdate life hook function can get the updated state
lazyLoad
Before use:
import OtherComponent from './OtherComponent';
After use:
import React, {lazy} from 'react'; const OtherComponent = lazy(() => import('./OtherComponent'));
This code will automatically import the package containing OtherComponent components when the component is rendered for the first time.
What is the lazy function?
- React. The lazy function allows you to deal with dynamically introduced components like rendering conventional components
- React.lazy accepts a function that needs to dynamically call import(). It must return a Promise that needs to resolve a react component of default export.
- The lazy component should then be rendered in the suspend component, so that we can use graceful degradation while waiting to load the lazy component.
- The fallback attribute of the suspend component accepts any React element (loading page) you want to show during component loading. You can place the suspend component anywhere above the lazy load component. You can even wrap multiple lazy load components with a suspend component.
Code case
The above language description is read-only. You can't understand it, or you have to understand it in combination with the code. If you don't say much, go to the code!
Lazy function combined with suspend component to realize lazy loading of routing
import React, { Suspense, lazy } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; const Home = lazy(() => import('./routes/Home')); const About = lazy(() => import('./routes/About')); const App = () => ( <Router> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route path="/" component={Home}/> <Route path="/about" component={About}/> </Switch> </Suspense> </Router> );
For the components introduced by the above code through the lazy function, the page will not be rendered. When you click to enter a component, you will load the component. When you click load components, if the network speed is slow, the loaded components or other React elements introduced by the suspend component fallback attribute will be displayed.
Why? Now there are only two components. If lazy loading is not applicable to 100 components, all 100 components need to be rendered for the first time, which prolongs the first screen loading time. Lazy loading is adopted, which can better improve the user experience. The loading speed of the first screen components is faster and solve the white screen problem.
Hook
What is React Hook?
- Hook is a new feature of React 16.8. It allows you to use state and other React features without writing class.
Three commonly used hooks
- state Hook:React.useState()
- Effect Hook:React.useEffect()
- Ref Hook:react.useRef()
state Hook
- state Hook allows function components to have state and read and write state data
- Syntax: const {XXX, setXXX} = react useState(initValue)
- useState() Description:
Parameter: the specified value is cached internally during the first initialization
Return value: contains data of 2 elements. The first parameter is a function. The second parameter specifies a new status value for the internal current. The internal uses it to overwrite the original status value
- Setxxx() can be written in two ways:
setXxx(newValue): if the parameter is a non function value, specify a new status value directly. It is used internally to overwrite the original status value
SetXXX (value = > newvalue): the parameter is a function that accepts the original status value and returns a new status value, which is used internally to overwrite the original status value
It is also the first case of clicking + 1:
import React from 'react' function demo(){ const [count,setCount] = React.useState(0) functon increment(){ setCount(count+1) } return( <div> <h2>The current summation is:{count}</h2> <button onClick={increment}>Point me+1</button> </div> ) }
Effect Hook
- Effect Hook allows you to perform side-effect operations in function components (used to simulate life cycle hooks in class components)
- Side effects in React:
Send ajax request for data acquisition
Set subscription / start timer
Manually change the real DOM
- Syntax and description
useEffect(() => { //Any operation with side effects can be performed here return () => { //Do some finishing work here, such as clearing timer / unsubscribing } },[stateValue]) {/*The second parameter [stateValue] has the meaning of detection. If [] is specified, The callback function will only be executed after the first render(). If the second parameter [] is not passed, This is equivalent to detecting the desired satte. The callback function will also be triggered when the state changes*/}
- You can think of useEffect Hook as a combination of the following three functions
componentDidMount()
componentDidUpdate()
componentWillUnmount()
Automatically + 1 after mounting:
import React from 'react' function demo(){ const [count,setCount] = React.useState(0) React.useEffect(() => { const timer = setInterval(() => { setCount(count+1) },500) return () => { clearInterval(timer) } },[]) function unMount(){ ReactDOM.unmountComponentAtNode(document.getElementById('root')) } return( <div> <h2>The current summation is:{count}</h2> <button onClick={unMount}>Click uninstall components</button> </div> ) }
Ref Hook
- Ref Hook can store / find component internal labels or any other data in function components
- Syntax: const myref = react useRef()
- Function: save label object, function and react Createref()
import React from 'react' function demo(){ const myRef = React.useRef() show(){ alert(myRef.current.value) } return( <div> <input type="text" ref={myRef]> <button onClick = {show}>Click prompt input Box information</button </div> ) }
Fragment
- Use: < fragment > < / fragment >
- Function: you don't have to have a real DOM and label
Let's take a simple example:
class Count extends React.Component{ render(){ return( <div> {/*The reason for the package < div > is that there is only one root element. In fact, it can be replaced by < fragment >, and this label will not be displayed in console printing*/} <div>... <input>... ... </div> ) } }
Context
understand
- A way of component communication, which is often used for the communication between ancestor components and descendant components
use
- Create Context container object: const xxcontext = react createContext()
- When rendering subcomponents, wrap the xxxcontext outside Provider, which passes data to descendant components through the value attribute
<XxxContext .Provider value={data}> </XxxContext .Provider>
- The descendant component reads data
//The first method: limited to class components static contextType = MyContext //Claim to receive context this.context
//The second way: both function components and class components can be used <XxxContext .Consumer value={data}> { value => { //Value is the value data in the context //show contents } } </XxxContext .Consumer>
case
const MyContext = React.createContext() const {Provider,Consumer} = MyContext //Ancestor component class A extends React.Component{ state = { useName:'A assembly' } render(){ const {useName} = this.state return( <div> <h2>I am A Component, user name:{useName}</h2> <Provider value={useName}> <B/> </Provider> </div> ) } } //Subcomponents class B extends React.Component{ render(){ return( <div> <C /> <D /> <h2>I am B assembly</h2> <h2>I from A The user name received by the component is:{}</h2> </div> ) } } //Sub component (class component) class C extends React.Component{ static contextType = MyContext //Claim to receive context render(){ return( <div> <h2>I am C assembly</h2> <h2>I from A The user name received by the component is:{this.context}</h2> </div> ) } } //Sub component (function component) function D(){ return( <div> <div> <h2>I am D assembly</h2> <h2>I from A The user name received by the component is: <Consumer> { value => { retrun `${value.useName}` } } <Consumer/> </h2> </div> </div> ) }