NavigatorIOS - 是否有viewDidAppear或viewWillAppear等效?

Dan*_*iel 9 react-native

我正在努力将应用程序移植到React-Native来测试它.当我回到导航器堆栈中的上一个视图(点击后退按钮)时,我想运行一些代码.是否有viewWillAppear方法?我在导航器上看到有一个"onDidFocus()"回调,听起来它可能是正确的东西..但似乎没有像NavigatorIOS那样的东西

Jic*_* Wu 13

我找到了一种在UIKit中模拟viewDidAppear和viewDidDisappear的方法,
但我不确定它是否是一种"正确"的方式.

componentDidMount: function() {
    // your code here

    var currentRoute = this.props.navigator.navigationContext.currentRoute;
    this.props.navigator.navigationContext.addListener('didfocus', (event) => {
        //didfocus emit in componentDidMount
        if (currentRoute === event.data.route) {
            console.log("me didAppear");
        } else {
            console.log("me didDisappear, other didAppear");
        }
        console.log(event.data.route);
     });
}, 
Run Code Online (Sandbox Code Playgroud)


Hik*_*abe 6

对于使用钩子和反应导航版本 5.x 的人,我认为您可以这样做以期望 viewDidAppear 的类似行为:

  import React, {useCallback } from "react";
  import { useFocusEffect } from "@react-navigation/native";

  const SomeComponent = () => {
      useFocusEffect(
        useCallback(() => {
          //View did appear
        }, [])
      );
      //Other codes
  }
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅https://reactnavigation.org/docs/use-focus-effect/


sho*_*226 -2

我创建了一个自定义按钮,用于按照https://github.com/facebook/react-native/issues/26onLeftButtonPress处理返回运行代码

解决这个问题的方法是在左侧设置自定义后退按钮,或者在 iOS 中实现 - viewWillDisappear: 。