Reactjs React.js应用程序中的Mapbox gl,TypeError:无法读取属性';setFeatureState';未定义的

Reactjs React.js应用程序中的Mapbox gl,TypeError:无法读取属性';setFeatureState';未定义的,reactjs,mapbox,mapbox-gl,Reactjs,Mapbox,Mapbox Gl,需要在地图上创建悬停效果,我将根据本教程进行操作: 不幸的是,我遇到了一个我无法解决的错误,请参见下面的错误堆栈: Uncaught TypeError: Cannot read property 'setFeatureState' of undefined at r.<anonymous> (Map.js:219) at r.delegates.o.<computed> (mapbox-gl.js:23210) at r.St.fire (ma

需要在地图上创建悬停效果,我将根据本教程进行操作:

不幸的是,我遇到了一个我无法解决的错误,请参见下面的错误堆栈:

Uncaught TypeError: Cannot read property 'setFeatureState' of undefined
    at r.<anonymous> (Map.js:219)
    at r.delegates.o.<computed> (mapbox-gl.js:23210)
    at r.St.fire (mapbox-gl.js:915)
    at HTMLDivElement.<anonymous> (mapbox-gl.js:23021)
添加console.log以进行调试


有人看到这个问题了吗?

这是因为您正在创建一个新函数并创建一个新的
实例。将其更改为箭头函数-

this.map.on('mousemove', 'contours', (e) => {  //arrow function//
                if (e.features.length > 0) {
                    if (hoveredStateId) {
                        console.log('hoveredStateId ',hoveredStateId)
                        this.map.setFeatureState(
                            { source: 'contours', id: hoveredStateId },
                            { hover: false }
                        )
                    }
                    console.log('e.features[0]',e.features[0])
                    console.log('e.features[0].id',e.features[0].id)
                    hoveredStateId = e.features[0].id
                    console.log('s',hoveredStateId)
                    this.map.setFeatureState(
                        { source: 'contours', id: hoveredStateId },
                        { hover: true }
                    )
                }
            })
您将面临与上述函数相同的函数错误,并将其更改为箭头函数-

   this.map.on('mouseleave', 'contours', () => {
            console.log('jestem 2')

            if (hoveredStateId) {
                this.map.setFeatureState(
                    { source: 'contours', id: hoveredStateId },
                    { hover: false }
                )
            }
            hoveredStateId = null
        }) 

        console.log('jestem 3 ',hoveredStateId )
        this.setLegend(data)
        this.setFill() 


    })

没错。你能解释一下为什么会有不同吗?在本期之前,我一直认为“function(){}”等于“()=>{}”。当您使用
function(){}
创建一个新函数时,它会创建它自己的
这个
的实例。使用es6 arrow函数不会创建该函数的新实例,而是使用其父函数this。
   this.map.on('mouseleave', 'contours', () => {
            console.log('jestem 2')

            if (hoveredStateId) {
                this.map.setFeatureState(
                    { source: 'contours', id: hoveredStateId },
                    { hover: false }
                )
            }
            hoveredStateId = null
        }) 

        console.log('jestem 3 ',hoveredStateId )
        this.setLegend(data)
        this.setFill() 


    })