首页 > 解决方案 > react-map-gl 警告 onViewportChange

问题描述

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

警告:在现有状态转换期间无法更新(例如在渲染中)。渲染方法应该是 props 和 state 的纯函数。

在此处输入图像描述

标签: reactjswarningsmapboxreact-map-gl

解决方案


我在 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 }) }
        }}
      />
    )
  }
}

推荐阅读