Service scenario: Tables A and B are brothers of each other. When an event in TABLE A is invoked, updates in table B need to be triggered.

Workaround: Use A publish-subscribe model, subscribe to events in Table A and notify table B when they are published

Code implementation:

export class SubscriptionPublish { private eventMap: Record<string, ((params: any) => any)[]>; constructor() { this.eventMap = {}; } /** * Subscribe function * @param key subscribe event key * @param handler subscribe event */ on(key: string, handler: (params: any) => any) {if (! this.eventMap[key]) { this.eventMap[key] = []; } this.eventMap[key].push(handler); Emit (key: string, params?);} /** * emit(key: string, params?); : any) { if (this.eventMap[key]) { this.eventMap[key].forEach((handler) => { handler(params); }); }} /** * @param key * @param handler */ remove(key: string, handler: params) Any) => any) {if (this.eventMap[key]) {// If (this.eventMap[key]) {const res = this.eventMap[key].indexof (handler); res ! == -1 && this.eventMap[key].splice(res, 1); }} // Create a global instance const defaultEvent = new SubscriptionPublish(); export default defaultEvent;Copy the code

Code usage: We create an instance of the publish-subscribe class after we write the code and use it globally

  • A form
const ApiTable: FC= () => { // ... // Refresh list method const loadApi = () => {table.reload(); }; UseEffect (() => {// Subscribe to the refresh method defaultevent.on ('loadApi', loadApi); Return () => {// When the component is destroyed, destroy the subscription function defaultevent.remove ('loadApi', loadApi); }; } []); return ( <> // ... Business code </>); }; export default ApiTable;Copy the code
  • B form
const Index: FC = () => { // ... Const handleSubmit = useCallback(async () => {//... Omit other logical processing // After publishing, the subscription function calls defaultevent.emit ('loadApi'); } []); return ( // ... Business code); }; export default Index;Copy the code

The publish-subscribe mode is specifically used to solve communication problems between sibling components, not just React. The same principle applies elsewhere, as does the Observer mode. I’m just writing this for my business scenario