更新地理位置值时无法读取未定义的 属性 'setState'

Cannot read property 'setState' of undefined while updating geolocation values

我正在尝试使用地理定位获取纬度和经度。我得到了值,但是当我尝试设置状态值时,它显示了这个错误。 "Cannot read property 'setState' of undefined"。可能是我在另一个函数中调用 setState 时出现此错误。

我还尝试创建另一个用于设置状态值的函数,但它也抛出 this is not defined 错误。这样做的正确方法是什么?

getLocation=()=>
    {
      navigator.geolocation.getCurrentPosition(function(position) {
        this.setState({venueLatitude:position.coords.latitude});
    this.setState({venueLongitude:position.coords.longitude});

      });
    }

this 不是指组件的实例。您可以阅读更多内容,例如:https://www.andrewconnell.com/blog/deal-with-undefined-this-react-event-handler-performant-way/

getLocation = () => {
    navigator.geolocation.getCurrentPosition((position) => {
        this.setState({ venueLatitude: position.coords.latitude });
        this.setState({ venueLongitude: position.coords.longitude });
    });
};