The React doc are unfortunately unclear for me at my level of understanding.
What cycle method should I use here instead of componentDidMount()? I want this component to update Google Map every time it gets new state from state.selectedShopInfo
.
In my app user is clicking some list and every time he clicks this component gets new data.
I'm checking it with console.log(_.last(this.props.selectedShopInfo));
and it is working.
So what React cycle method should I use so every time { selectedShopInfo: state.selectedShopInfo }
will change GoogleMap Component
will change as well?
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
class GoogleMap extends Component {
componentDidMount() {
const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
if (lastSelectedShopInfo !== undefined) {
new google.maps.Map(this.refs.map, {
zoom: 20,
center: {
lat: Number(lastSelectedShopInfo.latitude),
lng: Number(lastSelectedShopInfo.longitude),
},
});
}
}
render() {
console.log(_.last(this.props.selectedShopInfo));
return (
<div>
<hr />
<div className="google-map" ref="map" />
<hr />
</div>
);
}
}
function mapStateToProps(state) {
return { selectedShopInfo: state.selectedShopInfo };
}
export default connect(mapStateToProps)(GoogleMap);
Your component will re-render anytime a props
or state
change. This is the default behavior for React components.
So your component will re-render, but the logic you have in componentWillMount
will not be applied more than once.
To solve this, move that logic to a separate function and call that both in componentDidMount()
and in componentDidUpdate()
. Something like this:
componentDidMount() {
this.mapsInit();
}
componentDidUpdate(prevProps) {
if (JSON.stringify(this.props) !== JSON.stringify(prevProps)) {
this.mapsInit();
}
}
mapsInit() {
const lastSelectedShopInfo = _.last(this.props.selectedShopInfo);
if (lastSelectedShopInfo !== undefined) {
new google.maps.Map(this.refs.map, {
zoom: 20,
center: {
lat: Number(lastSelectedShopInfo.latitude),
lng: Number(lastSelectedShopInfo.longitude),
},
});
}
}
}
你应该首先呈现在地图中componentDidMount
并更新地图componentWillReceiveProps
。
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.