react-google-maps状态更新导致infoWindow进入无限循环渲染

时间:2018-08-07 09:02:18

标签: reactjs react-google-maps

所以我对react-google-maps有一个奇怪的问题,或者也许这是我对状态如何在react中工作的有限理解。

// @flow
import React, { Component } from 'react';
import { Marker } from 'react-google-maps';
import InfoBox from './InfoBox';

type MapMarkerPropsType = {
   offerId: number,
   location: Object,
}
type MapMarkerStateType = {
   isHovered: boolean,
}

class MapMarker extends Component<MapMarkerPropsType, 
   MapMarkerStateType> {
      constructor (props: MapMarkerPropsType) {
        super(props);

        this.state = {
          isHovered: false
        };
     }

onMouseOver = () => {
    //HERE you have access to offerId alter store
    console.log('onMouseOver', this.props.offerId);
    this.setState({ isHovered: true });
};

onMouseOut = () => {
    //HERE you have access to offerId alter store
    console.log('onMouseOut', this.props.offerId);
    this.setState({ isHovered: false });
};

render () {

    return (
        <div>
            {
                this.state.isHovered &&
                <InfoBox defaultPosition={this.props.location}/>
            }
            <Marker
                position={this.props.location}
                onMouseOver={this.onMouseOver}
                onMouseOut={this.onMouseOut}
                icon={`${window.location}/icons/Android.png`}
            />
        </div>
    );
 }
}

export default MapMarker;

这是不更改状态的工作方式(请查看控制台)

Without altering state

在这里,当我添加状态更改时

With state

1 个答案:

答案 0 :(得分:0)

确定正确阅读文档后,我了解到 <InfoBox defaultPosition={this.props.location}/>应该放在里面 <Marker/>