javascript - 在反应中使用发布订阅使组件卸载和安装
问题描述
我正在尝试在 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 次时的日志输出:
- 安装
- 发表
- 卸载
- 安装
- 发表
- 卸载
- 安装
- 发表
- 卸载
- 安装
解决方案
您是否尝试过在 useEffect 中添加第二个参数以便像 componentDidMount 一样使用它?我说的是空数组[]。您现在实现它的方式与 componentDidUpdate 相同,并在每次重新渲染时运行。
你可以在这里阅读更多
推荐阅读
- terraform - Terraform 空和非空块地图变量
- r - 在第一个匹配项下方填充每个 id 的数字
- reactjs - 未处理的拒绝(Typeerror):recipes.map 不是函数
- reactjs - 如何使用 React 实现 Django REST
- html - 文本重叠列在 100% 处大约 700 像素
- matlab - 如何在 MATLAB 中跟踪矩阵中所有连接的非零元素?
- c# - Entity Framework:获取元数据IProperty的DataType
- python-3.x - 根据先前值的条件替换列表中的值
- arrays - 数组类型'float [3]'不可分配。在C中复制二维数组
- r - 如何使用 datacamp 的教程包在 xaringan 幻灯片中插入 R 练习?