[英]Which React cycle method should I use to re-render component when redux state has changed?
就我的理解水平而言,不幸的是,React文档对我还不清楚。
我应该在这里使用哪种循环方法代替componentDidMount()? 我希望该组件每次从state.selectedShopInfo
获取新状态时更新Google Map。
在我的应用程序中,用户单击某些列表,每次单击该组件都会获取新数据。
我正在用console.log(_.last(this.props.selectedShopInfo));
它正在工作。
那么, 每次 { selectedShopInfo: state.selectedShopInfo }
更改时,我应该使用哪种React循环方法呢? GoogleMap Component
也会更改吗?
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);
只要props
或state
发生变化,您的组件就会重新渲染。 这是React组件的默认行为。
因此,您的组件将重新呈现,但是componentWillMount
的逻辑不会被多次应用。
要解决此问题,请将该逻辑移至单独的函数,然后在componentDidMount()
和componentDidUpdate()
调用。 像这样:
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.