react-google-maps 地图在传递道具时未更新,并且标记在更新时落后一个位置

Mat*_*ody 5 reactjs redux react-google-maps

我让地图在加载时工作,但每当我传递道具时,地图本身永远不会改变。

标记发生变化,但始终落后于它应有的状态,这显然是一个同步问题,但我不确定如何在我的组件中解决此问题。

class Map extends React.Component {
  state = {
     center: { lat: 50.937531, lng: 6.960278600000038 }
  }

  componentWillReceiveProps = () => {
    this.setState({
      center: { 
        lat: Number(parseFloat(this.props.city.lat)),
        lng: Number(parseFloat(this.props.city.lng))
      }
    });
  }

  render() {
    console.log(this.state.center)
    return (
      <div>
        <MapDetails
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-L-IikkM6BZ_3Z2QIzbkx4pdAkP76tok&v=3.exp&libraries=geometry,drawing,places"
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `100vh`}} />}
          mapElement={<div style={{ height: `100%` }} />}
          mapCenter={this.state.center}
        />
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return { city: state.CityNameReducer }
}

export default connect(mapStateToProps)(Map);

const MapDetails = withScriptjs(withGoogleMap(props =>
  <GoogleMap
    defaultZoom={12}
    defaultCenter={props.mapCenter}
  >
    <Marker
      position={props.mapCenter}
    />
  </GoogleMap>
));
Run Code Online (Sandbox Code Playgroud)

我最大的问题是为什么地图本身没有更新?

Saj*_*jed 6

为 GoogleMap 组件添加一个键。每次提供的密钥都应该是唯一的。对于您的测试,请使用 new Date().getTime() 函数。

<GoogleMap key={new Date().getTime()}/>
Run Code Online (Sandbox Code Playgroud)

正如我所提到的,它仅用于测试,因此请确保以更好的方式提供此密钥

  • @AslamShekh 每次触发渲染函数时,都会重新生成密钥,这会导致 GoogleMap 组件重新渲染。为了避免在 React 应用程序中进行如此广泛的渲染,这不应该是一个解决方案 (2认同)

Alb*_*ate -1

我可能建议您使用 shouldComponentUpdate(nextProps, nextState) {} 而不是 componentWillReceiveProps()。

我建议您阅读以下页面,以了解其工作原理。 更新和 componentWillReceiveProps

我没有关于组件父级中发生的情况的更多信息,因此我无法更深入地探讨该问题。但我认为你可以通过改变它来得到解决方案。