0

I was using const so that I could the navigation props for my screens. Now, I need to implement the componentDidMount(), but I have to switch to a class to do that. How can I have it so I can have the navigation props and class Component functionalities at the same time?

Code example:

Navigation.ts

import { ParamListBase, RouteProp } from "@react-navigation/native";
import { StackNavigationProp } from '@react-navigation/stack';

export interface StackNavigationProps<
    ParamList extends ParamListBase,
    RouteName extends keyof ParamList = string
>   {
    navigation: StackNavigationProp<ParamList, RouteName>;
    route: RouteProp<ParamList, RouteName>;
    onPress: () => void;
}

export type Routes = {
    Screen1: undefined;
    Screen2: undefined;
    Screen3: undefined,
};

Screen1.tsx

const Screen1 = ({ navigation }: StackNavigationProps<Routes, "Screen1">) => {
 ...
}

How can I combine the above and below to include navigation props and React.Component?

class Screen1 extends React.Component {

componentDidMount() {
    ...
  }
}

dannym
  • 95
  • 2
  • 10
  • You can use the useEffect hook to do the same task or the class will get the props the same way , try using this.props.navigation – Guruparan Giritharan May 05 '21 at 18:03
  • Does this answer your question? [How to call loading function with React useEffect only once](https://stackoverflow.com/questions/53120972/how-to-call-loading-function-with-react-useeffect-only-once) – Kai May 05 '21 at 18:52

1 Answers1

0

If you want to have componentDidMount method , you have not to use class component , you can use followings code instead in the functional programming:

React.useEffect(()=>{
   //Writing code here , have behavior like componentDidMount
  
   return () => {
     //Cleaning up , it's have behavior like componentWillUnmount
   }

} , []); //If you add dependency , it's have behavior like componentDidUpdate
MHP
  • 577
  • 5
  • 9