跳到內容
文件
進階
React Native

React Native

💡

升級至最新版本(≥ 1.0.0)以體驗此自訂功能。

與在瀏覽器中執行的 React 不同,React Native 具有非常不同的使用者體驗。例如,沒有「分頁焦點」,從背景切換到應用程式被視為「焦點」。若要自訂這些行為,您可以將預設的瀏覽器 focusonline 事件監聽器,取代為 React Native 的應用程式狀態偵測和其他原生移植的 API,並設定 SWR 以使用它們。

範例

全域設定

您可以將您的應用程式包裝在 SWRConfig 下,並在那裡預先設定所有設定

<SWRConfig
  value={{
    /* ... */
  }}
>
  <App>
</SWRConfig>

自訂 focusreconnect 事件

您需要處理一些設定,例如 isOnlineisVisibleinitFocusinitReconnect

isOnlineisVisible 是傳回布林值的函式,用於判斷應用程式是否「處於活動狀態」。預設情況下,如果未滿足這些條件,SWR 將會中止重新驗證。

當使用 initFocusinitReconnect 時,還需要設定自訂快取提供者。您可以使用空的 Map() 或您偏好的任何儲存空間。

<SWRConfig
  value={{
    provider: () => new Map(),
    isOnline() {
      /* Customize the network state detector */
      return true
    },
    isVisible() {
      /* Customize the visibility state detector */
      return true
    },
    initFocus(callback) {
      /* Register the listener with your state provider */
    },
    initReconnect(callback) {
      /* Register the listener with your state provider */
    }
  }}
>
  <App />
</SWRConfig>

讓我們以 initFocus 為例

import { AppState } from 'react-native'
 
// ...
 
<SWRConfig
  value={{
    provider: () => new Map(),
    isVisible: () => { return true },
    initFocus(callback) {
      let appState = AppState.currentState
 
      const onAppStateChange = (nextAppState) => {
        /* If it's resuming from background or inactive mode to active one */
        if (appState.match(/inactive|background/) && nextAppState === 'active') {
          callback()
        }
        appState = nextAppState
      }
 
      // Subscribe to the app state change events
      const subscription = AppState.addEventListener('change', onAppStateChange)
 
      return () => {
        subscription.remove()
      }
    }
  }}
>
  <App>
</SWRConfig>

對於 initReconnect,它需要一些第三方函式庫,例如 NetInfo(在新分頁中開啟) 以訂閱網路狀態。實作方式將與上述範例類似:接收 callback 函式,並在網路從離線恢復時觸發它,以便 SWR 可以開始重新驗證以保持您的資料為最新狀態。