Michael Du Michael Du - 2 months ago 6
Javascript Question

Child component won't update with new props after setState

I'm using the google-map-react module, passing in center coordinates that I would like to have updated after an API call. They are being passed in as props, from state of the parent component. However, when I update the state in the parent component, the child component () doesn't update, and I also see the following warning in my console:

GoogleMap: defaultCenter prop changed. You can't change default props.


I was expecting the child to re-render, but that isn't happening. Any thoughts?

const React = require('react')
const GoogleMap = require('google-map-react').default

const MapPage = React.createClass({
propTypes () {
return ({
params: object
})
},
getInitialState () {
return ({
zipSearch: this.props.params.zip || '90024',
initialCoordinates: [59.955413, 30.337844]
})
},
componentWillMount () {
$.get('www.APICALL.com', function (result) {
var resources = JSON.parse(result);
this.setState({
initialCoordinates: [parseFloat(resources[0].latitude), parseFloat(resources[0].longitude)]
})
}.bind(this));
},
render () {
var initialCoordinates = {lat: this.state.initialCoordinates[0], lng: this.state.initialCoordinates[1]}
console.log(initialCoordinates) //this gets logged twice in console.log
return (
<div className='map-container'>
<GoogleMap
defaultCenter={initialCoordinates}
defaultZoom={12}>
</GoogleMap>
</div>
)
}
})

module.exports = MapPage

Answer

The error says exactly what's wrong, you can't change the defaults. Set defaultCenter once, then use your dynamic state variable on center. Same thing with defaultZoom and zoom in case you need to change that.