簡體   English   中英

如何在不導航到另一個屏幕的情況下將信息從一個屏幕發送到另一個屏幕?

[英]How would I send information from one screen to another without navigating to the other screen?

我是 React Native 的新手,我一直在嘗試制作一個活動組織者,如果你注冊一個活動,它會被添加到另一個包含你的日程安排的頁面。 但是,我一直在查看文檔,但似乎無法找到如何在不實際導航到另一個屏幕的情況下將數據從一個屏幕發送到另一個屏幕。 換句話說,我想要這個navigation.navigate('Schedule', {name: eventName, time: eventTime}); 但沒有導航。

以下是一些建議:

1. AsyncStorage:您可以將它們保存到AsyncStorage(這是手機上的硬件支持的安全存儲),並且可以隨時檢索。 假設用戶的日程安排是這些事件的數組,例如:

 var a = [{ name: eventName, time: eventTime }, { name: eventName, time: eventTime }]

你可以這樣做:

AsyncStorage.setItem('Schedule', JSON.stringify(a));
AsyncStorage.getItem('Schedule');

請參閱: https : //github.com/react-native-community/async-storage

2.后端

將事件保存到您的后端服務器並從其他頁面檢索它們。

3. Redux 或 React Hooks(高級) https://medium.com/swlh/react-global-state-with-hooks-f163e49f90f9 https://redux.js.org/introduction/getting-started/

4. 帶有 React Hooks 的全局狀態

我最喜歡的使用內置 React Hooks 管理全局狀態的新方法

您可以擁有一個全局對象來存儲屏幕之間的共享數據。 即使您閱讀Redux文檔,redux 使用案例之一是當您有一些數據要在不同屏幕之間共享時。

所以這里是全局對象的代碼(單例模式)

export class GlobalState {
  public static getInstance(): GlobalState {
    if (GlobalState.instance == null) {
      GlobalState.instance = new GlobalState()
    }
    return GlobalState.instance
  }
private state: IGlobalState = this.restoreDefaultState()
private restoreDefaultState(): IGlobalState {
    return (
      {
        // your properties are placed here
      }
    )
  }
}

用法:

GlobalState.getInstance() ... //call any function placed there

注意:上面的代碼是用TypeScript編寫的,你可以很容易地將其轉換為JS

暫無
暫無

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

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