Summary of React component communication methods

1.props

Implement communication between parent and child components

//父组件
import './App.css';
import React, {
    
    useState } from 'react'
import Home from "./components/Home.jsx"

export default function App() {
    
    
  const [name,setName]=useState("zhangsan");
  return (
    <div>
      <Home name={
    
    name}/>
    </div>
  )
}


//子组件
import React from 'react'
export default function Home(props) {
    
    
  return (
    <div>name:{
    
    props.name}</div>
  )
}

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-NwpwjVs5-1668410196354) (E:%5Ctypora_data%5C%E7%AC%94%E8%AE%B0% E5%9B%BE%E7%89%87%5Cimage-20221114104019924.png)]

2. Message subscription publishing: pubs-sub

props can realize the communication between father and son, but there is no corresponding method for the communication between brothers. To realize it, you need to pass it layer by layer between multi-layer components, pass the information to the common parent component, and then the parent component The way to pass to subcomponents;

Solution:

By introducing the third-party library PubSubJS , you can directly publish messages in the component that triggers the event, and listen to subscribe messages in the component to realize the communication between sibling components:

Download third-party libraries

npm install pubsub-js --save

use

import React from 'react'
import PubSub from "pubsub-js"
import {
    
     Fragment } from 'react'
export default function Home(props) {
    
    
const send=()=>{
    
    
    //发布消息
    PubSub.publish("name",props.name)
}
  return (
    <Fragment>
      <div>name:{
    
    props.name}</div>
      &nbsp;&nbsp;&nbsp;<button onClick={
    
    send}>发布消息</button>
    </Fragment>
    
  )
}

import React,{
    
    useEffect,useState} from 'react'
import PubSub from 'pubsub-js'
export default function About() {
    
    
    const [name,setName]=useState("");
    useEffect(()=>{
    
    
        //订阅消息
       PubSub.subscribe("name",getName);
       return()=>{
    
    
           //组件卸载时,取消订阅
        PubSub.unsubscribe("name")
       }
    })
    const getName=(msg,data)=>{
    
    
       console.log("msg",msg)
       console.log("data",data)
       setName(data)
    }
  return (
    <div>&nbsp;&nbsp;&nbsp;name:{
    
    name}</div>
  )
}

3. Centralized management of react-redux

React-Redux is a plugin library to simplify using Redux in React.

download

npm install redux react-redux --save

Modify index.js

ProviderUse of components: Let all components get state data without passing it one by one

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {
    
     Provider } from 'react-redux';
import store from './redux/store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
      <React.StrictMode>
      <Provider store={
    
    store}>
      <App />
    </Provider>
      </React.StrictMode>
);

Create a redux folder and create the following files (when there are many states to be saved, action and reducer can also be created into a folder for easy management)

image-20221114145615539

//student_reducer.js
/**
 * reducer的作用
 * 用于初始化状态,加工状态
 * 根据旧状态和action产生新状态
 */
export default function studentReducer(preState=[],action){
    
    
    const {
    
    type,data}=action;
    switch(type){
    
    
        case 'addStudent':
            //不要再原有的preState身上修改,因引preState虽然内容变了,但是数组地址没变,React会认为状态没有改变而不会重新渲染页面
            return  [...preState,data];
        default:
            return preState;
    }

}
//student_action.js
/**
*表示动作的对象,包含 2 个属性,type和data
*type :标识属性,值为字符串,唯一,必须属性
*data :数据属性,类型任意,可选属性
*/
export  function addAction(data){
    
    
    return {
    
    type:"addStudent",data:data}
}

//store.js
/**
*Redux 核心对象,内部维护着 state 和 reducer
*/
import {
    
    createStore,combineReducers} from "redux";
import studentReducer from "./student_reducer.js";
//汇中所有的reducers
const allReducer=combineReducers({
    
    
    students:studentReducer
})
const store=createStore(allReducer);
export default store;

use:

useSelector(): The user obtains a certain item of data in the data warehouse store. This hook will subscribe to the redux store, so every time the redux state is updated, the selector in useSelector() will be recalculated, return a new result, and re-render the current components

//Student.jsx
import React from 'react'
import {
    
     useSelector } from 'react-redux'
import {
    
     Fragment } from 'react'
export default function Student() {
    
    
       const students=useSelector(state=>state.students)
  return (
    <Fragment>
      <ul>
        {
    
    students.map((item)=>{
    
    
          return <li key={
    
    new Date()}>name:{
    
    item.name}&nbsp;&nbsp;&nbsp;age:{
    
    item.age}</li>
        })}
      </ul>
    </Fragment>
  )
}

useDispatch(): update data

//Add.jsx
import React,{
    
    Fragment,useRef}from 'react'
import {
    
    useDispatch } from 'react-redux'
import {
    
     addAction } from '../redux/student_action';
export default function Student() {
    
    
   const dispatch=useDispatch();
   const name=useRef();
   const age=useRef();
   const add=()=>{
    
    
    console.log(name.current)
    const student={
    
    name:name.current.value,age:age.current.value}
    //更新数据
    dispatch(addAction(student))
   }
  return (
    <div>
        <Fragment>
        name:<input type="text" ref={
    
    name}/><br/>
        age:<input type="text" ref={
    
    age}/><br/>
        <button onClick={
    
    add}>添加</button>
    </Fragment>
    </div>
  )
}
//App.js

import './App.css';
import React from 'react'
import Student from "./components/Student.jsx"
import Add from "./components/Add.jsx"
export default function App() {
    
    
  return (
    <div>
      <Add/>
      <Student />
    </div>
  )
}

Effect:
https://gitee.com/cao-yanlei/image/raw/master/img/202211141523325.gif

4. Summary

Recommended Use:

  • Parent-child components: props
  • Brother components: message subscription-publishing, react-redux
  • Grandparents and grandchildren components (cross-level components): message subscription-publishing, react-redux

Guess you like

Origin blog.csdn.net/CYL_2021/article/details/127848217