【发布时间】:2019-03-06 00:11:03
【问题描述】:
我有一个从父组件获取数据的 MapBox 组件。
我试图避免每次父组件中发生状态更改时更新组件。即使 shouldComponentUpdate 记录相同的道具,它也会更新...
componentDidMount(){
if(this.props.data.features !== null){
this.fetchMap();
}
}
shouldComponentUpdate(nextProps) {
console.log('now:', this.props.data)
console.log('next', nextProps.data)
if (this.props.data === nextProps.data) {
return false;
}
if (this.props.data !== nextProps.data) {
return true;
}
return false;
}
componentDidUpdate(prevProps) {
if (this.props.data !== prevProps.data) {
this.fetchMap();
}
}
fetchMap() {
const { data } = this.props
const map = new mapboxgl.Map({
container: this.mapContainer,
style: 'mapbox://styles/mapbox/light-v9',
center: [8.32, 60.44],
zoom: 5,
})
map.on('load', () => {
map.addSource('locations', {
type: 'geojson',
data
});
});
}
.... render and return bla bla
家长:
const Parent () => {
const [state, change] = useState(false)
return (
<Button onClick={change(!state)}>Sorter</Button> // click and <Map> rerenders
<Map setDraw={setDraw} data={geojson} />
)
}
【问题讨论】:
-
不要尝试
===比较,而是尝试shallowCompare或使用React.PureComponent,看看是否有帮助。 -
简化这个` if (this.props.data === nextProps.data){return false;} if(this.props.data !== nextProps.data) {return true;}`返回
this.props!==nextProps -
@Panther 我尝试更改为
React.PureComponent并删除shouldComponentUpdate。它仍然重新渲染。浅比较不是一回事吗? -
那么是调试的好时机。基本上你需要编写自己的浅表比较,看看哪些 props 发生了变化,它们为什么会发生变化以及如何避免它。
-
@Panther 最好的前进方式是什么?可能是因为数据对象比较大而且嵌套比较大,所以不理解没有区别?
标签: javascript reactjs mapbox mapbox-gl-js