首页 > 解决方案 > 在反应中使用发布订阅使组件卸载和安装

问题描述

我正在尝试在 reactjs 中实现 pubsub(发布订阅)。每次侦听事件时,组件都会卸载,然后再次安装。以下是组件:

组分A

单击按钮时,使用有效负载(即项目)发布事件。

import PubSub from 'pubsub-js';
import React from 'react';
import { Button } from 'react-native';

interface ComponentAProps {}

const ComponentA: React.FC<ComponentAProps> = ({}) => {
  return (
    <Button
      title="add items"
      onPress={() => {
           console.log('published')
           PubSub.publish('ADD_ITEMS', { item: { title: 'someItem' } })
        }
      }
    />
  );
};

export default ComponentA;

组分B

侦听事件(如果有),将有效负载添加到项目。呈现项目。

import React, { useEffect, useState } from 'react';
import { Text, View } from 'react-native';

interface ComponentBProps {}

interface IItem {
  title: string;
}

type IItems = IItem[];

const ComponentB: React.FC<ComponentBProps> = ({}) => {
  const [items, setItems] = useState<IItems>([]);

  useEffect(() => {
    console.log('mounted');
    /**
     * add item to items
     */
    PubSub.subscribe('ADD_ITEMS', (item: IItem) => {
      setItems([...items, item]);
    });
    return () => {
      console.log('unmounted');
      PubSub.unsubscribe('ADD_ITEMS');
    };
  });

  let renderItems = items.map((item) => (
    <View>
      <Text>{item.title}</Text>
    </View>
  ));

  return <View>{renderItems}</View>;
};

export default ComponentB;

以下是单击按钮 3 次时的日志输出:

标签: javascriptreactjsreact-nativepublish-subscribe

解决方案


您是否尝试过在 useEffect 中添加第二个参数以便像 componentDidMount 一样使用它?我说的是空数组[]。您现在实现它的方式与 componentDidUpdate 相同,并在每次重新渲染时运行。

你可以在这里阅读更多


推荐阅读