Issue in the compoentDidMount actions?
Problem:
I am creating react native application with Google maps. This is how my code is structured.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Dimensions,
Button,
TouchableOpacity
} from "react-native";
import { MapView } from "expo";
import {
Ionicons,
Foundation,
Entypo,
MaterialCommunityIcons
} from "@expo/vector-icons";
const windowheight = (Dimensions.get("window").height * 80) / 100;
const windowwidth = (Dimensions.get("window").width * 80) / 100;
class Parking extends Component {
static navigationOptions = {
title: "Parking",
headerStyle: {
backgroundColor: "#06153b"
},
headerTintColor: "#fff",
headerTitleStyle: {
color: "#ffff"
}
};
state = {
focusedLocation: {
latitude: 6.9218374,
longitude: 79.8211859,
latitudeDelta: 0.0322,
longitudeDelta:
(Dimensions.get("window").width / Dimensions.get("window").height) *
0.0322
},
locationChosen: false,
placesList:
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
}
reloadLocation = () => {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
};
pickLocationHandler = event => {
this.setState({ locationChosen: true });
const coords = event.nativeEvent.coordinate;
let placesList = ;
let places = ;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
const apikey = "myKey";
fetch(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
coords.latitude +
"," +
coords.longitude +
"&radius=800" +
"&type=parking" +
"&key=" +
apikey
)
.then(response => response.json())
.then(responseJson => {
if (responseJson) {
placesList = responseJson.results;
placesList.map((el, index) => {
var place = {
title: el.name,
coordinates: {
latitude: el.geometry.location.lat,
longitude: el.geometry.location.lng
}
};
places.push(place);
});
this.setState({ placesList: places });
}
});
};
componentWillUnmount = () => {
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: 0,
longitude: 0
},
locationChosen: false,
placesList:
};
});
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
const places = this.state.placesList;
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => (this.map = ref)}
>
{places.map((place, index) => {
return (
<MapView.Marker
key={index}
coordinate={place.coordinates}
title={place.title}
pinColor="violet"
/>
);
})}
{marker}
</MapView>
</View>
);
}
}
export default Parking;
const styles = StyleSheet.create({
container: {
width: "100%",
alignItems: "center",
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10
},
map: {
height: "100%",
width: "100%"
},
button: {
margin: 8
},
callout: {},
calloutButton: {
marginTop: windowheight,
marginLeft: windowwidth,
borderWidth: 1,
borderColor: "rgba(0,0,0,0.2)",
alignItems: "center",
justifyContent: "center",
width: 50,
height: 50,
backgroundColor: "#2b78fe",
borderRadius: 100,
shadowColor: "#e9ebee"
}
});
In the componentDidmount method, I am getting the users current location and render the map according to that. When I open the app and go this page which in this component It loads the map as I needed but when I go to another component and come again to this component it just loads the map according to the place in the state. Can someone help me to solve this problem and Is their way to load the map with new location automatically, when the user's location changes?Thank you!
react-native
add a comment |
Problem:
I am creating react native application with Google maps. This is how my code is structured.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Dimensions,
Button,
TouchableOpacity
} from "react-native";
import { MapView } from "expo";
import {
Ionicons,
Foundation,
Entypo,
MaterialCommunityIcons
} from "@expo/vector-icons";
const windowheight = (Dimensions.get("window").height * 80) / 100;
const windowwidth = (Dimensions.get("window").width * 80) / 100;
class Parking extends Component {
static navigationOptions = {
title: "Parking",
headerStyle: {
backgroundColor: "#06153b"
},
headerTintColor: "#fff",
headerTitleStyle: {
color: "#ffff"
}
};
state = {
focusedLocation: {
latitude: 6.9218374,
longitude: 79.8211859,
latitudeDelta: 0.0322,
longitudeDelta:
(Dimensions.get("window").width / Dimensions.get("window").height) *
0.0322
},
locationChosen: false,
placesList:
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
}
reloadLocation = () => {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
};
pickLocationHandler = event => {
this.setState({ locationChosen: true });
const coords = event.nativeEvent.coordinate;
let placesList = ;
let places = ;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
const apikey = "myKey";
fetch(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
coords.latitude +
"," +
coords.longitude +
"&radius=800" +
"&type=parking" +
"&key=" +
apikey
)
.then(response => response.json())
.then(responseJson => {
if (responseJson) {
placesList = responseJson.results;
placesList.map((el, index) => {
var place = {
title: el.name,
coordinates: {
latitude: el.geometry.location.lat,
longitude: el.geometry.location.lng
}
};
places.push(place);
});
this.setState({ placesList: places });
}
});
};
componentWillUnmount = () => {
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: 0,
longitude: 0
},
locationChosen: false,
placesList:
};
});
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
const places = this.state.placesList;
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => (this.map = ref)}
>
{places.map((place, index) => {
return (
<MapView.Marker
key={index}
coordinate={place.coordinates}
title={place.title}
pinColor="violet"
/>
);
})}
{marker}
</MapView>
</View>
);
}
}
export default Parking;
const styles = StyleSheet.create({
container: {
width: "100%",
alignItems: "center",
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10
},
map: {
height: "100%",
width: "100%"
},
button: {
margin: 8
},
callout: {},
calloutButton: {
marginTop: windowheight,
marginLeft: windowwidth,
borderWidth: 1,
borderColor: "rgba(0,0,0,0.2)",
alignItems: "center",
justifyContent: "center",
width: 50,
height: 50,
backgroundColor: "#2b78fe",
borderRadius: 100,
shadowColor: "#e9ebee"
}
});
In the componentDidmount method, I am getting the users current location and render the map according to that. When I open the app and go this page which in this component It loads the map as I needed but when I go to another component and come again to this component it just loads the map according to the place in the state. Can someone help me to solve this problem and Is their way to load the map with new location automatically, when the user's location changes?Thank you!
react-native
add a comment |
Problem:
I am creating react native application with Google maps. This is how my code is structured.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Dimensions,
Button,
TouchableOpacity
} from "react-native";
import { MapView } from "expo";
import {
Ionicons,
Foundation,
Entypo,
MaterialCommunityIcons
} from "@expo/vector-icons";
const windowheight = (Dimensions.get("window").height * 80) / 100;
const windowwidth = (Dimensions.get("window").width * 80) / 100;
class Parking extends Component {
static navigationOptions = {
title: "Parking",
headerStyle: {
backgroundColor: "#06153b"
},
headerTintColor: "#fff",
headerTitleStyle: {
color: "#ffff"
}
};
state = {
focusedLocation: {
latitude: 6.9218374,
longitude: 79.8211859,
latitudeDelta: 0.0322,
longitudeDelta:
(Dimensions.get("window").width / Dimensions.get("window").height) *
0.0322
},
locationChosen: false,
placesList:
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
}
reloadLocation = () => {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
};
pickLocationHandler = event => {
this.setState({ locationChosen: true });
const coords = event.nativeEvent.coordinate;
let placesList = ;
let places = ;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
const apikey = "myKey";
fetch(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
coords.latitude +
"," +
coords.longitude +
"&radius=800" +
"&type=parking" +
"&key=" +
apikey
)
.then(response => response.json())
.then(responseJson => {
if (responseJson) {
placesList = responseJson.results;
placesList.map((el, index) => {
var place = {
title: el.name,
coordinates: {
latitude: el.geometry.location.lat,
longitude: el.geometry.location.lng
}
};
places.push(place);
});
this.setState({ placesList: places });
}
});
};
componentWillUnmount = () => {
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: 0,
longitude: 0
},
locationChosen: false,
placesList:
};
});
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
const places = this.state.placesList;
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => (this.map = ref)}
>
{places.map((place, index) => {
return (
<MapView.Marker
key={index}
coordinate={place.coordinates}
title={place.title}
pinColor="violet"
/>
);
})}
{marker}
</MapView>
</View>
);
}
}
export default Parking;
const styles = StyleSheet.create({
container: {
width: "100%",
alignItems: "center",
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10
},
map: {
height: "100%",
width: "100%"
},
button: {
margin: 8
},
callout: {},
calloutButton: {
marginTop: windowheight,
marginLeft: windowwidth,
borderWidth: 1,
borderColor: "rgba(0,0,0,0.2)",
alignItems: "center",
justifyContent: "center",
width: 50,
height: 50,
backgroundColor: "#2b78fe",
borderRadius: 100,
shadowColor: "#e9ebee"
}
});
In the componentDidmount method, I am getting the users current location and render the map according to that. When I open the app and go this page which in this component It loads the map as I needed but when I go to another component and come again to this component it just loads the map according to the place in the state. Can someone help me to solve this problem and Is their way to load the map with new location automatically, when the user's location changes?Thank you!
react-native
Problem:
I am creating react native application with Google maps. This is how my code is structured.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Dimensions,
Button,
TouchableOpacity
} from "react-native";
import { MapView } from "expo";
import {
Ionicons,
Foundation,
Entypo,
MaterialCommunityIcons
} from "@expo/vector-icons";
const windowheight = (Dimensions.get("window").height * 80) / 100;
const windowwidth = (Dimensions.get("window").width * 80) / 100;
class Parking extends Component {
static navigationOptions = {
title: "Parking",
headerStyle: {
backgroundColor: "#06153b"
},
headerTintColor: "#fff",
headerTitleStyle: {
color: "#ffff"
}
};
state = {
focusedLocation: {
latitude: 6.9218374,
longitude: 79.8211859,
latitudeDelta: 0.0322,
longitudeDelta:
(Dimensions.get("window").width / Dimensions.get("window").height) *
0.0322
},
locationChosen: false,
placesList:
};
componentDidMount() {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
}
reloadLocation = () => {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
};
pickLocationHandler = event => {
this.setState({ locationChosen: true });
const coords = event.nativeEvent.coordinate;
let placesList = ;
let places = ;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
const apikey = "myKey";
fetch(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
coords.latitude +
"," +
coords.longitude +
"&radius=800" +
"&type=parking" +
"&key=" +
apikey
)
.then(response => response.json())
.then(responseJson => {
if (responseJson) {
placesList = responseJson.results;
placesList.map((el, index) => {
var place = {
title: el.name,
coordinates: {
latitude: el.geometry.location.lat,
longitude: el.geometry.location.lng
}
};
places.push(place);
});
this.setState({ placesList: places });
}
});
};
componentWillUnmount = () => {
this.setState(prevState => {
return {
focusedLocation: {
...prevState.focusedLocation,
latitude: 0,
longitude: 0
},
locationChosen: false,
placesList:
};
});
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
const places = this.state.placesList;
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => (this.map = ref)}
>
{places.map((place, index) => {
return (
<MapView.Marker
key={index}
coordinate={place.coordinates}
title={place.title}
pinColor="violet"
/>
);
})}
{marker}
</MapView>
</View>
);
}
}
export default Parking;
const styles = StyleSheet.create({
container: {
width: "100%",
alignItems: "center",
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10
},
map: {
height: "100%",
width: "100%"
},
button: {
margin: 8
},
callout: {},
calloutButton: {
marginTop: windowheight,
marginLeft: windowwidth,
borderWidth: 1,
borderColor: "rgba(0,0,0,0.2)",
alignItems: "center",
justifyContent: "center",
width: 50,
height: 50,
backgroundColor: "#2b78fe",
borderRadius: 100,
shadowColor: "#e9ebee"
}
});
In the componentDidmount method, I am getting the users current location and render the map according to that. When I open the app and go this page which in this component It loads the map as I needed but when I go to another component and come again to this component it just loads the map according to the place in the state. Can someone help me to solve this problem and Is their way to load the map with new location automatically, when the user's location changes?Thank you!
react-native
react-native
asked Nov 20 '18 at 5:54
dwpdwp
15810
15810
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Its because, you are using StackNavigator and the componentDidMount only get called in the mounting phase.
When you navigate to maps component first time componentDidMount is called, When you navigate to some other component from maps component(maps component doesn't get unmounted in case of stack navigator). When you navigate back it just focuses/updates the already mounted maps component and componentDidMount will not get called. Hopefully render and componentDidUpdate gets called.
If you dont want to change the logic then:
One solution to this problem is instead of navigate() use push(),
this.props.navigation.push(routeName) //react-navigation-v3
push() function will push the new route component into the satck rather than navigating to previous same component in the stack.
This differs from navigate() in that navigate will pop back to earlier in the stack if a route of the given name is already present there. push will always add on top, so a route can be present multiple times.
Second Solution You might wanna check this alternative approach
class MyComponent extends React.Component {
state = {
isFocused: false
};
componentDidMount() {
this.subs = [
this.props.navigation.addListener("didFocus", () => this.setState({ isFocused: true })),
this.props.navigation.addListener("willBlur", () => this.setState({ isFocused: false }))
];
}
componentWillUnmount() {
this.subs.forEach(sub => sub.remove());
}
render() {
// ...
}
}
Third Solution
When you navigate back, also set the state(current location) in componentDidUpdate Note. you need a condition before setting the state in componentDidUpdate, other wise you will end up triggring infinite loop.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387030%2fissue-in-the-compoentdidmount-actions%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Its because, you are using StackNavigator and the componentDidMount only get called in the mounting phase.
When you navigate to maps component first time componentDidMount is called, When you navigate to some other component from maps component(maps component doesn't get unmounted in case of stack navigator). When you navigate back it just focuses/updates the already mounted maps component and componentDidMount will not get called. Hopefully render and componentDidUpdate gets called.
If you dont want to change the logic then:
One solution to this problem is instead of navigate() use push(),
this.props.navigation.push(routeName) //react-navigation-v3
push() function will push the new route component into the satck rather than navigating to previous same component in the stack.
This differs from navigate() in that navigate will pop back to earlier in the stack if a route of the given name is already present there. push will always add on top, so a route can be present multiple times.
Second Solution You might wanna check this alternative approach
class MyComponent extends React.Component {
state = {
isFocused: false
};
componentDidMount() {
this.subs = [
this.props.navigation.addListener("didFocus", () => this.setState({ isFocused: true })),
this.props.navigation.addListener("willBlur", () => this.setState({ isFocused: false }))
];
}
componentWillUnmount() {
this.subs.forEach(sub => sub.remove());
}
render() {
// ...
}
}
Third Solution
When you navigate back, also set the state(current location) in componentDidUpdate Note. you need a condition before setting the state in componentDidUpdate, other wise you will end up triggring infinite loop.
add a comment |
Its because, you are using StackNavigator and the componentDidMount only get called in the mounting phase.
When you navigate to maps component first time componentDidMount is called, When you navigate to some other component from maps component(maps component doesn't get unmounted in case of stack navigator). When you navigate back it just focuses/updates the already mounted maps component and componentDidMount will not get called. Hopefully render and componentDidUpdate gets called.
If you dont want to change the logic then:
One solution to this problem is instead of navigate() use push(),
this.props.navigation.push(routeName) //react-navigation-v3
push() function will push the new route component into the satck rather than navigating to previous same component in the stack.
This differs from navigate() in that navigate will pop back to earlier in the stack if a route of the given name is already present there. push will always add on top, so a route can be present multiple times.
Second Solution You might wanna check this alternative approach
class MyComponent extends React.Component {
state = {
isFocused: false
};
componentDidMount() {
this.subs = [
this.props.navigation.addListener("didFocus", () => this.setState({ isFocused: true })),
this.props.navigation.addListener("willBlur", () => this.setState({ isFocused: false }))
];
}
componentWillUnmount() {
this.subs.forEach(sub => sub.remove());
}
render() {
// ...
}
}
Third Solution
When you navigate back, also set the state(current location) in componentDidUpdate Note. you need a condition before setting the state in componentDidUpdate, other wise you will end up triggring infinite loop.
add a comment |
Its because, you are using StackNavigator and the componentDidMount only get called in the mounting phase.
When you navigate to maps component first time componentDidMount is called, When you navigate to some other component from maps component(maps component doesn't get unmounted in case of stack navigator). When you navigate back it just focuses/updates the already mounted maps component and componentDidMount will not get called. Hopefully render and componentDidUpdate gets called.
If you dont want to change the logic then:
One solution to this problem is instead of navigate() use push(),
this.props.navigation.push(routeName) //react-navigation-v3
push() function will push the new route component into the satck rather than navigating to previous same component in the stack.
This differs from navigate() in that navigate will pop back to earlier in the stack if a route of the given name is already present there. push will always add on top, so a route can be present multiple times.
Second Solution You might wanna check this alternative approach
class MyComponent extends React.Component {
state = {
isFocused: false
};
componentDidMount() {
this.subs = [
this.props.navigation.addListener("didFocus", () => this.setState({ isFocused: true })),
this.props.navigation.addListener("willBlur", () => this.setState({ isFocused: false }))
];
}
componentWillUnmount() {
this.subs.forEach(sub => sub.remove());
}
render() {
// ...
}
}
Third Solution
When you navigate back, also set the state(current location) in componentDidUpdate Note. you need a condition before setting the state in componentDidUpdate, other wise you will end up triggring infinite loop.
Its because, you are using StackNavigator and the componentDidMount only get called in the mounting phase.
When you navigate to maps component first time componentDidMount is called, When you navigate to some other component from maps component(maps component doesn't get unmounted in case of stack navigator). When you navigate back it just focuses/updates the already mounted maps component and componentDidMount will not get called. Hopefully render and componentDidUpdate gets called.
If you dont want to change the logic then:
One solution to this problem is instead of navigate() use push(),
this.props.navigation.push(routeName) //react-navigation-v3
push() function will push the new route component into the satck rather than navigating to previous same component in the stack.
This differs from navigate() in that navigate will pop back to earlier in the stack if a route of the given name is already present there. push will always add on top, so a route can be present multiple times.
Second Solution You might wanna check this alternative approach
class MyComponent extends React.Component {
state = {
isFocused: false
};
componentDidMount() {
this.subs = [
this.props.navigation.addListener("didFocus", () => this.setState({ isFocused: true })),
this.props.navigation.addListener("willBlur", () => this.setState({ isFocused: false }))
];
}
componentWillUnmount() {
this.subs.forEach(sub => sub.remove());
}
render() {
// ...
}
}
Third Solution
When you navigate back, also set the state(current location) in componentDidUpdate Note. you need a condition before setting the state in componentDidUpdate, other wise you will end up triggring infinite loop.
edited Nov 23 '18 at 9:40
answered Nov 20 '18 at 6:15
ShivamShivam
1,1821332
1,1821332
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53387030%2fissue-in-the-compoentdidmount-actions%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown