【问题标题】:How to refresh app when opened from deeplink?从深度链接打开时如何刷新应用程序?
【发布时间】:2024-05-18 04:25:02
【问题描述】:

我正在为反应原生应用而苦苦挣扎。我会实现 react native firebase 动态链接,但现在我有点迷失了。我在 HomeScreen 上使用这种方法,每次有人打开应用程序时都能完美运行。

async componentWillMount() {
    try {
      let url = await firebase.links().getInitialLink();
      if(url) {
        let api = "example.com/user/123456";
        try {
          this.setState({ data: "John Doe" });
          this.props.navigation.navigate('Preview', {user: this.state.data })
        }
        catch {
        }
      }
    }
    catch {
    }
  }

但是当应用程序已经打开时,此方法无法正常工作。有没有一种方法可以让我每次有人回到打开的应用时触发一个功能?

【问题讨论】:

    标签: firebase react-native firebase-dynamic-links


    【解决方案1】:

    提示一下,您应该将代码放在componentDidMount 中,这样您就不会阻塞初始(第一次)渲染。

    您可以使用AppState 来监听被置于后台/前台的应用程序的变化。

    componentDidMount() {
      this.showPreview();
      AppState.addEventListener('change', this.onAppStateChange);
    }
    
    componentWillUnmount() {
      AppState.removeEventListener('change', this.onAppStateChange);
    }
    
    const onAppStateChange = appState => {
      // You can check if appState is active/background/foreground
      this.showPreview();
    }
    
    const showPreview = async (appState) => {
        // You can check if appState is active/inactive/background
        try {
          let url = await firebase.links().getInitialLink();
          if(url) {
            let api = "example.com/user/123456";
            try {
              this.setState({ data: "John Doe" });
              this.props.navigation.navigate('Preview', {user: this.state.data })
            }
            catch {
            }
          }
        }
        catch(e) {
          console.error(e);
        }
    }
    

    【讨论】: