React Native通过Linking接收并处理App Link或Deep Link的链接

当React Native的项目从外部链接启动时, 有一个较为方便的方法来处理该链接用于获取变量或跳转到相应的页面: Linking.getInitialURL

import { Linking } from 'react-native';
import URL from 'url';
componentDidMount() {
  Linking.getInitialURL().then(url) => {
    if (url) {
      const { protocol, host, pathname, search, query } = URL.parse(url);    // 解析url
      console.log(`url is: ${protocol}://${host}${pathname}${search}`)
    }
  }).catch(err => console.error('An error occurred', err));
}

但是,该方法仅在app启动时触发,若需要在app开启期间(位于后台)处理跳转到App的链接,需要用另一个方法来监听

import URL from 'url';
componentDidMount() {
  Linking.addEventListener('url', this._handleOpenURL);
},
componentWillUnmount() {
  Linking.removeEventListener('url', this._handleOpenURL);
},
handleURL(event) {
  const { protocol, host, pathname, search, query } = URL.parse(event.url);    // 解析url
  console.log(`url is: ${protocol}://${host}${pathname}${search}`)
}

你可能感兴趣的:(React Native通过Linking接收并处理App Link或Deep Link的链接)