I am using react-redux and react-navigation with my react native app.
I have a component called photolist that gets all the photos from a database. There are two screens that call this component. The userProfile screen passes true and userId to photolist for the user's photos; the feed screen passes false and null to photolist for the all the photos.
In App.js, I put the Feed screen and User screen in the same stack so I can navigate easily.
With this approach, I am able to load the main page on App load, see all the photos, then go to a user's page and see the user's photos. But from the user's page, when I click the back button to go back to the main page, no photos are loaded anymore. Note that in this sequence of actions, the photolist component's componentDidMount() function is called exactly twice; when going back to the main feed from userProfile, it is not called again.
Any idea on why is this happening and how may I resolve this? Is there a way to keep the navigation structure where clicking the back button from userProfile will take you back to where you were in the main feed page without needing to reload the main feed again?
photolist.js:
class PhotoList extends React.Component {
constructor(props) {
super(props);
}
componentDidMount = () => {
const { isUser, userId } = this.props;
// load a single user's photos or all photos
if (isUser) {
this.props.loadFeed(userId);
} else {
this.props.loadFeed();
}
}
render(){
return (
<View style={{flex:1}}>
<FlatList
data = {(this.props.isUser) ? this.props.userFeed : this.props.mainFeed}
keyExtractor = {(item, index) => index.toString()}
...
/>
</View>
)
}
}
const mapStateToProps = state => {
return {
mainFeed: state.feed.mainFeed,
userFeed: state.feed.userFeed
}
}
const mapDispatchToProps = {
loadFeed
};
export default connect(mapStateToProps, mapDispatchToProps)(PhotoList);
feed.js:
<PhotoList isUser={false} navigation={this.props.navigation}/>
userProfile.js:
<PhotoList isUser={true} userId={this.state.userId} navigation={this.props.navigation}/>
App.js:
const FeedScreenStack = createStackNavigator({
FeedStack: { screen: feed },
UserProfile: { screen: userProfile }
});
shouldComponentUpdatelifecycle method to check ifloadFeed()should be called? I see how it would work if I am on the same screen, but I am navigating between screens here. I can't just check for something likeshouldComponentUpdate(nextProps, _) { if (nextProps.navigation.state.routeName === "UserProfile") { return false } return true }- JAMthis.props.loadFeedmethod is overwriting the same data when you navigate from Feed -> User. Could you store the data in a different location? Then you wouldn't have to worry about it being overwritten. - Ross Allen