“This is the second day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

Previously: After creating a component, how do you handle state changes within the component and value transfers between components? As a beginner, from the documentation, a little hands-on experience is what follows. I hope there is something wrong, the bigwigs are generous.

Props

Function component & Class component

Note: For a class component, props is mounted on the component, so you need to get this. For function components, props is a pass parameter, so just use it.

Function component: accepts a props object with only data and returns a React element. It's essentially a JS function
function welcome(props) {
      return <h1>Hello, {props.name}</h1>
}

ReactDom.render(
    welcome,
    document.getElementById('root'))/ / class components
class welcome extends React.component {
    render() {
        return <h1>Hello, {this.props.name}</h1>}}Copy the code

State

Components are completely private and controlled only by the current component

setState

// function form
this.setState((props, state) = > {})

// Object form: In the same cycle, the value called first is overwritten by the value called later
this.setState({ counter: 2 })
Copy the code

Note when using:

  1. Instead of modifying state directly, use setState

    // wrong
    this.state.comment = 'hello'
    
    // correct
    this.setState({ comment: 'hello' })' // ----- hooks: useState ----- const [visible, setVisible] = useState(false); handleVisible = (visible) => { setVisible(visible) }Copy the code
  2. Updates to this.props and this.state can be asynchronous, so you can’t rely on their values to update the next state. You need to use the callback form of setState to get the current state and props.

    // wrong
    this.setState({ counter: this.state.counter + this.props.increment })
    
    // correct: Pass parameters to obtain the current state & props
    this.setState((state, props) = > ({
      counter: state.counter + props.increment
    }))
    
    // --- or ---
    this.setState(function(state, props) {
      return { counter: state.counter + props.increment }
    })
    Copy the code
  3. State updates are merged

    When you call setState(), React merges your supplied objects into the current state, which can be updated separately by calling setState()

    class MyComponent extends React.component {
      constructor(props) {
        super(props) // Pass props to the parent constructor
        this.state = {
          date: new Date()}}componentDidMount() {
        this.timerID = setInterval(
          () = > this.tick(),
          1000
        );
      }
    
      componentWillUnmount() {
        clearInterval(this.timerID);
      }
    
      tick() {
        this.setState({
          date: new Date()}); }render() {
        return (
          <div>
            <h1>Hello, world!</h1>
            <h2>This is {this.state.date.toLocaleTimeString()}.</h2>
          </div>
        )
      }
    }
    
    ReactDOM.render(<MyComponent/>.document.getElementById('root')
    
    
    /* 1.myComponent to reactdom.render, React calls the MyComponent constructor. This.state 2. React calls the render() method of the component. React Updates the DOM to match the output rendered by the MyComponent component. After the output of MyComponent is inserted into the DOM, React calls the componentDidMount() lifecycle method (ask the browser to set a timer to call the component's tick() method once per second). Call the tick() method once per second: Components schedule a UI update by calling setState. When you call setState, React will know that the state has changed, and will recall Render () to determine what the page displays. Because this.state.date changes, MyComponent prints the updated time and React updates DOM 5. Once the MyComponent is removed from the DOM, React calls the componentWillUnmount() lifecycle method and the timer stops */
    Copy the code

In combination withhooksLook at thesetState

When setState is called, the update to the component state is queued and React is informed that it needs to rerender the component and its children with the updated state. It is the primary means of updating the user interface and response time processors and processing server data.

From the above description we know:

  1. setStateIs a command that requests an update instead of updating the component immediately

    React delays calls and then updates multiple components at once, without guaranteeing that state changes take effect immediately. If there is a need to setState immediately after reading this. State, need to use componentDidUpdata or setState callback function (setState(updater, callback), ensure that the update triggered.

  2. SetState will always perform a re-render unless shouldComponentUpdate returns false

  3. If the update return value is exactly the same as the current state, the rendering will be skipped

Use the code

import React, { useState } from 'react'
export default(props? :any) = > {// useState, define a state variable count, pass in the initial state argument, return the current state and the function to update the state
    // Array destruct: useState returns two values, each with a custom name
    const [count, setCount] = useState(0); // this.count = 0
    const [fruit, setFruit] = useState('banana')
    return (
        <div>/ / read the count<p>You clicked {count} times</p>// Update count: Pass a new value to setCount. React will re-render the Example component and pass the latest count to it<button onClick={()= > setCount(count + 1)}> Click me</button>
        </div>)}Copy the code