react-map-gl 警告 onViewportChange

react-map-gl Warning onViewportChange

我正在测试版本为“4.0.0-beta.3”(https://github.com/uber/react-map-gl) 的库示例,但我对方法 onViewportChange 有此警告:

Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.

已解决的问题:版本 4.0.0-beta.4 https://github.com/uber/react-map-gl/issues/642

我在 4.1.13 上得到这个。

您可以通过仅在安装组件后响应onViewportChange来解决警告:

class Map extends Component {
  state = {
    viewport: {
      width: 400,
      height: 400,
      latitude: -33.9249,
      longitude: 18.4241,
      zoom: 8
    },
    mounted: false
  }

  componentDidMount () {
    this.setState({ mounted: true })
  }

  render () {
    const { mounted } = this.state
    return (
      <ReactMapGL
        mapboxApiAccessToken={<token>}
        {...this.state.viewport}
        onViewportChange={(viewport) => {
          if (mounted) { this.setState({ viewport }) }
        }}
      />
    )
  }
}