地图启动时出现 React-mapbox-gl-draw 错误

React-mapbox-gl-draw error on map startup

我刚开始在我的 react-mapbox-gl 应用程序中使用 react-mapbox-gl-draw。我正在按照 this very quick demo and their docs 设置 <DrawControl />。看起来很简单,但我 运行 遇到了问题。

这是我的代码,错误如下:

import DrawControl from 'react-mapbox-gl-draw';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
// imports 

// ignore the class instantiation, constructor, all that. It works. 

// in the render method: 

<Map
 onStyleLoad={ el => this.map = el} 
 style={this.state.style}
 containerStyle={{
    height: this.state.height,
    width: this.state.width
 }}
 center={[0,0]}
 zoom={[2]} >

     <DrawControl />

</Map>

这是错误:

index.js:14 Uncaught TypeError: map.getStyle is not a function
    at DrawControl.componentDidMount (index.js:14)
    at commitLifeCycles (react-dom.development.js:14361)
    at commitAllLifeCycles (react-dom.development.js:15462)
    at HTMLUnknownElement.callCallback (react-dom.development.js:100)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
    at invokeGuardedCallback (react-dom.development.js:187)
    at commitRoot (react-dom.development.js:15603)
    at completeRoot (react-dom.development.js:16618)
    at performWorkOnRoot (react-dom.development.js:16563)
    at performWork (react-dom.development.js:16482)
    at performSyncWork (react-dom.development.js:16454)
    at requestWork (react-dom.development.js:16354)
    at scheduleWork (react-dom.development.js:16218)
    at Object.enqueueSetState (react-dom.development.js:11299)
    at ReactMapboxGl.../../../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:335)
    at r.<anonymous> (map.js:119)
    at r.Ft.fire (mapbox-gl.js:29)
    at r._render (mapbox-gl.js:33)
    at mapbox-gl.js:33

或多或少,显然 <DrawControl /> 试图在组件(地图)安装后立即调用一个方法,但我不确定为什么或如何修复它。我将不胜感激任何帮助和建议!

-编辑- 我在我的地图对象中添加了一个 MapContext.Consumer,因为它抱怨想要一个 map 对象。所以现在它正在安装,但我看不到绘图对象。有任何想法吗?

这是我更新后的代码:

<Map
 onStyleLoad={ el => this.map = el} 
 style={this.state.style}
 containerStyle={{
    height: this.state.height,
    width: this.state.width
 }}
 center={[0,0]}
 zoom={[2]} >

    <MapContext.Consumer>
         {(map) => {
              <DrawControl />
         }}
    </MapContext.Consumer>

</Map>

所以解决方案是在 MapContext.Consumer 中实施 MapboxDraw。下面是 MapboxDraw 的片段,下面是 link。这是可行的,因为它可以访问地图对象并可以直接在地图上绘制。

var draw = new MapboxDraw({
   displayControlsDefault: false,
   controls: {
   polygon: true,
   trash: true
   }
});