react component communication

Use of state and setState

State: initialize data value
Deconstruct the initial value in state in the render function: for example, const {count} = this state;
setState: used to update data
Master various uses of setState:
Syntax: setState(updater, [callback])

  • updater: update data FUNCTION/OBJECT
  • Callback: callback FUNCTION after successful update
  • Asynchronous: react usually gathers a batch of components that need to be updated, and then updates them at one time to ensure the performance of rendering
  • Shallow merge object Assign() to manually merge multi-level data
  • After calling setState, the lifecycle is triggered to re render the component
 //When the page has multiple setstates, react gathers a batch of updated components, and then updates them at one time to ensure the rendering performance
 class App extends Component {
 state = {
    count: 1,
    nub: {
      number: 5,
      name: "React"
    }
  }
render() {
//Get the initial value in the state
  const { count, time, nub } = this.state;
    return <div>
      <p>count:{count}</p>
      <button onClick={() => {
        this.setState(()=>{
              count: count + 1
        },()=>{
        //Callback
          console.log("Component update complete");
        });
      }}>Count Increasing</button>
      <p>nub: {nub.number}</p>
      //Multi level array merging
      <button onClick={() => {
        this.setState({
          nub: {
            ...nub,
            number: nub.number + 5,
          }
        })
      }}>nub.number Increasing</button>
   
    </div>
}
}
export default App;

Communication between components

Master the communication between React components:
Communication between components:

  1. Pass information from parent component to child component:
  • When a parent component calls a child component, the information to be passed is added to the properties of the child component, similar to: name={nameVal}
  • The child component receives the information passed by the parent component through the props attribute,

Parent component:

import { Component } from "react";
import List from "./list";

class App extends Component {
  state = {
    val:'content', 
   }
  
  render() {
    const {val} = this.state;
   
    return <div>
      <List name={val}/>
    </div>
  }
}
export default App;

Subcomponents:

import { Component } from "react";

class list extends Component {
    render(){
    //Deconstruct the value or method passed by the parent component
      const { name} = this.props;
      return<div>
        <p>{name}</p>
      </div>
    }
}

export default list;
  1. Pass information from child component to parent component:
  • Define the relevant callback function on the parent component and pass the callback function to the child component,
  • The child component calls the callback function of the parent to communicate with the parent

Parent component

import { Component } from "react";
import List from "./list";

class App extends Component {
  state = {
    openKey : "family",
    val:'content', 
   }
   //Define callback function
  alterVal=(val)=>{
    this.setState({
      openKey: val
    });

  }
  
  render() {
    const {openKey, val,} = this.state;
    return <div>
      { openKey}
      <List name={val}
      //Pass the defined function to the child
         alterVal={this.alterVal}/>
    </div>
  }
}
export default App;

Subcomponents

import { Component } from "react";

class list extends Component {
    render(){
    //Receiving data and methods transmitted from superior components
      const {  name,alterVal } = this.props;
      return<div>
        <p>{name}</p>
        <button onClick={()=>{
        //Changing data using callback functions
           alterVal('Modified')
        }}>Subcomponents</button>
      </div>
    }
}

  1. Cross component Tongxin

  2. Intermediate components transfer props layer by layer

  3. Using context objects
    The first method: use the props of intermediate components to transfer data. If the parent component has a deep level, each intermediate component has to transfer props, which increases the complexity. These props are not required by each layer of components. When the nesting level is too deep, this method needs to be considered.
    The second method provides a method to transfer data between component trees without manually adding props to each layer of components.
    Context is equivalent to a global variable. Put the communication data into the context, and the communication data in the context can be obtained at any level of the component, so there is no need to transfer props layer by layer.

     1.Called in parent component Provider Transfer data
     2.Specify in the subcomponent to be obtained contextType Read current Context Incoming communication data
    
//context.js
import {createContext} from "react";
const context = createContext();
const {Provider,Consumer} = context;
export {Provider,Consumer};
export default context;
Parent component:
//app.js
import {Provider} from "./context";//Introducing encapsulated providers
//Data and methods of communication
 state = {val:'content', }
  alterVal=(val)=>{
    this.setState({
      openKey: val
    });
  }
 render(){ 
      return<div>
  <Provider
     value={{
        val:val,
        alterVal:this.alterVal
  }}>
       <List/>
  </Provider>
<div>
      }
//list.js   
  render(){ 
      return<Li/>   
      }
//Li1.js
//The first way is to use the static attribute to take the value static contextType = context in the context;
import context from "./context";//Gets the stored contextType
 static contextType = context;
    render(){
      // const {  name,alterVal } = this.props;
      const {  val,alterVal } = this.context;
      console.log(val,)
      return<div>
        <p>{val}</p>
        <button onClick={()=>{
           alterVal('Modified 3333')
        }}>Subcomponents</button>
      </div>
    }
//Li2.js
//The second way is to wrap the value with Consumer. The parameters in the callback function are the values in context 
import { Consumer } from "./context";
 render(){
  return  <Consumer>
     {(context)=>{
              console.log(context);
                return <div>
                  <button onClick={()=>{
           alterVal('Modified 3333')
        }}>Subcomponents</button>
                </div>
             }}
       </Consumer>}

Keywords: React

Added by rich_d on Sun, 19 Dec 2021 04:32:17 +0200