我无法将Google地图多边形设置为null使用react

时间:2018-11-24 00:55:45

标签: reactjs google-maps google-maps-api-3

我定义了HOC Map

export default WrappComponent =>
  class Map extends Component {
    this.state = {
        mapIsReady: false,   // is google map load
    }
    componentDidMount() {
        // create script element
        ....
        script.addEventListener('load', () => this.setState({ mapIsReady: true }))
        .....
    }
    render () {
        ...
        return <WrappedComponent {...this.props} mapIsReady={this.state.mapIsReady}/>
    }
}

开发组件:

class DrawPlot extends Component {
 this.state = {
    hidden: false
 }
 componentDidUpdate(prevProps, prevState) {
    if (prevProps.mapIsReady !== this.props.mapIsReady) {
        // init google map
        this.map = new window.google.maps.Map(dom, {
            // other option: draw polygon..
        })

        // use renderPloygon functin
        this.renderPloygon(this.map) // it's worked, but if i change this.map => null nothing on map
    }

    if(prevState.hidden !== this.state.hidden) {
        console.log('state is changed')    // still worked
        this.renderPloygon(null)    // Ooops! they polygon still on map
    }
}

// render the polygon
renderPloygon (map) {
    let data = [
        {lat: xxx, lng: xxx},
        {lat: xxx, lng: xxx},
        {lat: xxx, lng: xxx}
    ]
    var bermudaTriangle = new window.google.maps.Polygon({
      paths: data,
      strokeColor: '#ff6f06',
      fillColor: '#ff6f06',
      fillOpacity: .5,
      strokeWeight: 1,
      strokeOpacity: 1,
      clickable: false,
    })
    bermudaTriangle.setMap(map)
}

hiddenPolygon() {
    // this.renderPloygon(null)   didn't work

    // so i try to change the state. and use `componentDidUpdate` lifecicle but still not work
    this.setState({hidden: true})
}

render () {
   return (
       ....
       <button onclick={this.hiddenPolygon.bind(this)}>Hidden</button>
       ....
   )
 }
}

export default Map(DrawPlot)

我使用了基本的htmljs,它是完美的显示和隐藏的多边形,但是没有反应,为什么?

0 个答案:

没有答案