”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 在 React 中的选项卡之间发送数据。

在 React 中的选项卡之间发送数据。

发布于2024-11-08
浏览:561

Send data between tabs in React.

本文将介绍如何在 React 全局组件之间发送数据,甚至在不同的浏览器选项卡中也是如此。


故事

想象您有一个项目列表,例如用户。

每个用户都可以在模态窗口中打开进行修改。

您没有任何后端订阅,这意味着如果用户发生变化,用户列表不会自动与后端同步。

因此,一旦用户的个人资料更新,您希望自动刷新模式窗口下的用户列表(甚至在网站的所有其他选项卡中)。

我们将如何同步这些不相关的组件和选项卡中的数据?


解决方案

模态窗口和用户列表应该能够交换事件和数据。

因此,如果在模态窗口中执行操作,则应将事件发送到等待此类操作的所有组件(例如用户列表),以便它们可以对此事件做出反应,例如,通过正在同步数据。

让我们通过使用一个小包 use-app-events 在“UserList”和“UserProfileModal”组件之间建立这样的通信:

const UserProfileModal = () => {
  // retrieve a user ID from URL, for example
  const { userId } = useParams();

  // 1. Create an instance of useAppEvents
  const { notifyEventListeners } = useAppEvents();

  const submitUpdate = async () => {
    // send a request to BE here, await the response...

    // 2. Send an event containing the updated user ID to
    // all other components that are listening for it
    notifyEventListeners('user-update', userId);
  };

  return ;
};

模态窗口

用户列表

const UserList = () => {
  const [users, setUsers] = useState([]);

  // 1. Create an instance of useAppEvents
  const { listenForEvents } = useAppEvents();

  // 2. Listen and wait for the 'user-update' event to happen in the app
  listenForEvents('user-update', (userId) => {
    // 3. React to the occurred event by loading the refreshed
    // list of users from BE here...
  });

  return users.map((user) => (
    // render users here...
  ));
};

use-app-events 是一个小型开源包,没有依赖性和风险,它也得到积极维护并且使用安全。

此时,UserProfileModal中用户个人资料的更新会自动通知UserList等所有监听器,从而触发UserList中用户列表的刷新,从而带来更好的UX。

UserList 和 UserProfileModal 放置在组件树中的哪个位置并不重要,它们仍然能够在彼此之间发送数据,即使在不同的浏览器选项卡中


结论

如果您需要轻松设置全局通信以在组件之间交换数据 - 请使用 use-app-events 包。

它提供了易于使用的 API、丰富的文档和严格的类型,以确保您拥有最佳的开发人员体验。

版本声明 本文转载于:https://dev.to/maqs/send-data-between-tabs-in-react-obk?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3