簡體   English   中英

當應用程序處於后台狀態時,深度鏈接不起作用 React Native

[英]Deep linking not working when app is in background state React native

我正在創建基於 React native 的電子商務應用程序。這里我需要從 url shared 打開單個產品頁面。實際上,當應用程序處於終止狀態時它會工作,但如果應用程序處於后台/非活動狀態,它將無法工作。 在后台/非活動狀態下打開時,共享 url 為空。我附上了我的代碼。

// following code working for app killing state

componentWillMount() {

    if (Platform.OS === 'android') {
      console.log("Testing");debugger

      //Constants.OneTimeFlag == false;
          Linking.getInitialURL().then(url => {
            console.log(url);
            var str = url
            var name = str.split('/')[4]
            Constants.isLinking = true;
           this.setState({ shop_Id: name})


           if (str)
           {
            this.setState({ isFromHomeLinking:'FROM_LINK' })
            this.props.navigation.navigate('SingleProductScreen', { ListViewClickItemHolder: [this.state.shop_Id,1,this.state.isFromHomeLinking] });

           }


          });

    }

    else {
        Linking.addEventListener('url', this.handleNavigation);
      }

  }

Not working code following..



componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
}

componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

this.state.appState declared in constructor(props)

_handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
     console.log('App has come to the foreground!');debugger
 if (Platform.OS === 'android') {
          console.log("Testing");debugger

          //Constants.OneTimeFlag == false;
              Linking.getInitialURL().then(url => {
                console.log(url);
                var str = url
                var name = str.split('/')[4]
                Constants.isLinking = true;
               this.setState({ shop_Id: name})


               if (str)
               {
                this.setState({ isFromHomeLinking:'FROM_LINK' })
                this.props.navigation.navigate('SingleProductScreen', { ListViewClickItemHolder: [this.state.shop_Id,1,this.state.isFromHomeLinking] });

               }


              });

        }

        else {
            Linking.addEventListener('url', this.handleNavigation);
          }
    }
    }

當我在后台狀態下從 whatsapp 和應用程序打開外部鏈接 Linking.getInitialURL() 接收為 null ..

以下我在清單文件中

<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
 <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
 <category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http"
 android:host="demo1.zgroo.com" />
</intent-filter>
      </activity>

以下是我的示例網址..

http://demo1.zgroo.com/xxxx

請讓我知道任何解決方案..

提前致謝..

您需要為這種情況注冊鏈接偵聽器。

componentDidMount() {
  Linking.addEventListener('url', this._handleOpenURL);
},
componentWillUnmount() {
  Linking.removeEventListener('url', this._handleOpenURL);
},
_handleOpenURL(event) {
  console.log(event.url);
}

更多https://facebook.github.io/react-native/docs/linking

這是使用鈎子的 Anurag 答案的一個版本:

export function useDeepLinkURL() {
  const [linkedURL, setLinkedURL] = useState<string | null>(null);

  // 1. If the app is not already open, it is opened and the url is passed in as the initialURL
  // You can handle these events with Linking.getInitialURL(url) -- it returns a Promise that
  // resolves to the url, if there is one.
  useEffect(() => {
    const getUrlAsync = async () => {
      // Get the deep link used to open the app
      const initialUrl = await Linking.getInitialURL();
      setLinkedURL(decodeURI(initialUrl));
    };

    getUrlAsync();
  }, []);

  // 2. If the app is already open, the app is foregrounded and a Linking event is fired
  // You can handle these events with Linking.addEventListener(url, callback)
  useEffect(() => {
    const callback = ({url}: {url: string}) => setLinkedURL(decodeURI(url));
    Linking.addEventListener('url', callback);
    return () => {
      Linking.removeEventListener('url', callback);
    };
  }, []);

  const resetURL = () => setLinkedURL(null);

  return {linkedURL, resetURL};
}

然后您可以將其用於:

const {linkedURL, resetURL} = useDeepLinkURL();

useEffect(() => {
    // ... handle deep link
    resetURL();
}, [linkedURL, resetURL])

我添加了函數resetURL因為如果用戶與應用程序共享同一個文件兩次,你會想要加載它兩次。 但是,由於深層鏈接最終會相同,因此不會再次觸發useEffect 您可以通過將linkedURL設置為null 來再次觸發它,因此下次共享文件時,您可以確定它會導致useEffect運行。

此外,我使用decodeURI對傳入的 URL 進行解碼,因為如果您使用像 react-native-fs 這樣的庫從指定路徑加載文件,它將無法處理名稱中帶有空格的文件,除非您使用decodeURI .

componentwillunmount刪除偵聽器。 無需在componentwillunmount編寫任何代碼,因為鏈接的addListener將始終偵聽,只有當您從后台(通過單擊新的深層鏈接)進入活動狀態時才會觸發。

暫無
暫無

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

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