」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在 React 中的選項卡之間發送資料。

在 React 中的選項卡之間發送資料。

發佈於2024-11-08
瀏覽:204

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