react-message subscription publishing mechanism (functional components pass values across components)

Install the PubSubJS tool library

npm install pubsub-js --save

A component subscribes to the message

import React, { useState } from "react";
import PubSub from "pubsub-js";
export default function ComponentA() {
  const [num, selectNum] = useState(0);
  //消息订阅
  PubSub.subscribe("pubAdd", (_, stateObj) => {
    selectNum(num + stateObj * 1);
  });

  return (
    <div>
      <h2>子组件A:{num}</h2>
      <hr />
    </div>
  );
}

B component publishes a message

import React, { useRef } from "react";
import PubSub from "pubsub-js";
export default function ComponentB() {
  const inputRef = useRef();

  function handleAdd() {
    // 消息发布
    PubSub.publish("pubAdd", inputRef.current.value);
  }
  return (
    <div>
      <h2>子组件B</h2>
      <select ref={inputRef} name="" id="">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button onClick={handleAdd}>添加</button>
      <hr />
    </div>
  );
}

Unsubscribe before uninstalling components

Use the return function of useEffect to unsubscribe before the component is destroyed

import React, { useState, useEffect } from "react";
import PubSub from "pubsub-js";
export default function ComponentA() {
  const [num, selectNum] = useState(0);
  const handleAdd = (subName, data) => {
    console.log(subName, data);
    selectNum(num + data * 1);
  };
  //消息订阅
  const addSub = PubSub.subscribe("pubAdd", handleAdd);
  useEffect(() => {
    return () => {
      // 卸载组件前取消订阅
      PubSub.unsubscribe(addSub);
    };
  }, []);

  return (
    <div>
      <h2>子组件A:{num}</h2>
      <hr />
    </div>
  );
}

Guess you like

Origin blog.csdn.net/yxlyttyxlytt/article/details/130958129