I read on some tutorials that we can pass a specific key in parameters of setState in order to update only specific elements. But here is my case :
I use tomchentw's react-google-maps component. I set the options of the map in my App state (then I pass it to the GoogleMap component via props).
app.jsx
constructor() {
super();
//Initial value
this.state = {
optionsMap:{
center: {
lat: 46.8261444,
lng: 2.2418121
},
zoom: 5
},
variables: {}
}
}
map.jsx
render() {
return (
<GoogleMapLoader
containerElement={ <div {...this.props} style={{ height: '500px'}}></div> }
googleMapElement={
<GoogleMap
ref="googleMap"
{...this.props.optionsMap} //biding map options with spread
onIdle={this._handleIdle.bind(this)}>
</GoogleMap>
}
/>
);
}
_handleIdle(event) {
this.props.updateVarsOptions(this.props.optionsMap);
}
When I call my updateVarOptions() function (when I moove the map) define in app.jsx, I update the state on the very specific key variables .
app.jsx
_updateVarsOptions(mapOptions) {
this.setState({
variables : mapOptions
});
}
So, I update only the variables key on the state, but when I do the setState, the map is resettings with the default value (center position and zoom). The state is updating the optionsMap key to. I don't understand why.
The reason why your map is updating with the default values from optionsMap
is because any call to setState
will cause the component to re-render (unless there is behavior defined in shouldComponentUpdate
that says otherwise). This, in turn, will re-render your Google Maps element and pass the information from the optionsMap
again, which has not changed since the initial render.
You might want to take a look at the shouldComponentUpdate
lifecycle function . This function is involked immediately before rendering, and its return value will tell your component whether or not it should call its render
function again. By default, it always returns true. You can modify this behavior such that your component will not re-render if the variables
state has changed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.