Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NavigatorIOS - Is there a viewDidAppear or viewWillAppear equivalent?

Tags:

react-native

I'm working on porting an app to React-Native to test it out. When I pop back to a previous view in the navigator stack (hit the back button) I'd like to run some code. Is there a viewWillAppear method? I see on the Navigator there is a "onDidFocus()" callback which sounds like it might be the right thing.. but there doesn't appear to be anything like that on NavigatorIOS

like image 473
Daniel Avatar asked Apr 14 '15 05:04

Daniel


3 Answers

For people who are using hooks and react navigation version 5.x, I think you can do this to expect similar behavior of viewDidAppear:

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

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

For more information, refer https://reactnavigation.org/docs/use-focus-effect/

like image 76
Bubu Avatar answered Nov 08 '22 15:11

Bubu


I find a way to simulate viewDidAppear and viewDidDisappear in UIKit,
but i'm not sure if it's a "right" way.

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);
     });
}, 
like image 14
Jichao Wu Avatar answered Nov 08 '22 14:11

Jichao Wu


Here is a solution to simulate viewDidAppear with latest React Navigation version:

componentDidMount() {
     var currentRoute = this.props.navigation.state.routeName;
     this.props.navigation.addListener('didFocus', (event) => {

         if (currentRoute === event.state.routeName) {
             // VIEW DID APPEAR
         }
     });
}

Thanks Jichao Wu for the idea :)

like image 1
Floris M Avatar answered Nov 08 '22 15:11

Floris M