簡體   English   中英

在反應中使用發布訂閱使組件卸載和掛載

[英]using publish subscribe in react makes the component to unmount and mount

我正在嘗試在 reactjs 中實現發布訂閱(發布訂閱)。 每次監聽事件時,組件都會卸載,然后再次安裝。 以下是組件:

組件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 次時日志的輸出:

  • 已安裝
  • 發表
  • 未安裝
  • 已安裝
  • 發表
  • 未安裝
  • 已安裝
  • 發表
  • 未安裝
  • 已安裝

您是否嘗試在 useEffect 中添加第二個參數以便像 componentDidMount 一樣使用它? 我說的是空數組 []。 您現在實現它的方式與 componentDidUpdate 相同,並且在每次重新渲染時運行。

你可以在這里閱讀更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM