Issue
I'm using react-navigation for my mobile app and I have 2 routes- Home and Favoriti, where Home is initial route. Both of those components have componentDidMount. Whenever I navigate to Favoriti from Home, Favoriti component mounts, but when I navigate back to Home, its componentDidMount doesn't execute. It only executes the first time I open the app, but I need it to mount every time I navigate to it.
import { createStackNavigator, createAppContainer} from 'react-navigation';
import Home from './views/Home';
import Favoriti from './views/Favoriti';
const MainNavigator = createStackNavigator({
FavoritiRT: Favoriti,
HomeRT: Home
},
{
initialRouteName: "HomeRT"
}
);
const MyRoutes = createAppContainer(MainNavigator);
export default MyRoutes;
There is no error showing, it's just that componentDidMount of initial route doesn't execute every time I navigate to it, but with other routes it does.
Solution
"componentDidMount" does not run again because the "Home" component has already been created and will continue to exist as long as it is in the stack. That instance of the Home component will be reused and the user will continue where they left off when they go back to that Home component. To run componentDidMount again you need to start a new instance of the Home component.
Instead of using the back button. Create a button and in the onPress prop navigate to a new instance of Home using the push method.
<Button
title="Home"
onPress={() => this.props.navigation.push('Home')}
/>
https://reactnavigation.org/docs/en/navigating.html#going-back
Edit:
While this will get your app running for now; sfratini makes a good point and his answer will be better for you if you end up working for a company/client or publish your own app. Adding a listener would be ideal for all the reasons he said.
Answered By - Raymond Mutyaba
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.