2

我正在为一个反应原生应用程序而苦苦挣扎。我会实现 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 {
    }
  }

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

4

1 回答 1

4

只是提示,您应该将代码放入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);
    }
}
于 2018-12-18T09:43:49.710 回答