首页 > 解决方案 > 设置状态导致 TypeError: this is undefined

问题描述

我在状态设置为的第 20 行有以下错误showNoResultsMessage

TypeError: this is undefined

我认为这可能是由于调用“this”的上下文存在问题。但是,我不确定如何解决这个问题,或者this在设置状态时在这种情况下会发生什么。我猜它是空的,需要以某种方式通过。

任何帮助,将不胜感激。提前致谢。

import React from 'react';
import ReactDOM from 'react-dom';

class MainApp extends React.Component {
    constructor(props) {
        super(props);        
        this.getLocation();
    }

    getPlaces(position) {
        const mainDiv = document.querySelector("#main-app");
        const mapTag = mainDiv.getAttribute('data-map');
        let apiUrl = "https://example.com/places.json";

        const url = apiUrl + "?lat=" + position.coords.longitude + "&lon=" + position.coords.latitude + "&tags=" + mapTag;

        console.log("mapag: " + mapTag);
        console.log("url: " + url);
        this.setState({showNoResultsMessage: true});
    };

    /**
     *  Could not get location, present error message
     */
    locationErrorHandler(err) {
        if (err.code == 1) {
            alert("Error: Access is denied!");
        } else if (err.code == 2) {
            alert("Error: Position is unavailable!");
        }
    }

    /**
     * First attempts to get location and from there, runs the api call to get places.
     */
    getLocation() {
        if (navigator.geolocation) {
            // timeout at 60000 milliseconds (60 seconds)
            var options = {timeout: 60000};
            navigator.geolocation.getCurrentPosition(this.getPlaces, this.locationErrorHandler, options);
        } else {
            alert("Sorry, browser does not support geolocation!");
        }
    }

    render() {
        return (
            <div>
                <div>Get Started</div>
            </div>
        );
    }
}

ReactDOM.render(
    <MainApp/>,
    document.getElementById('main-app')
)

标签: javascriptreactjscallback

解决方案


您应该像这样绑定构造函数中的函数:

this.getLocation.bind(this);

或使用如下箭头函数语法:

 getLocation = () => {
    if (navigator.geolocation) {
        // timeout at 60000 milliseconds (60 seconds)
        var options = {timeout: 60000};
        navigator.geolocation.getCurrentPosition(this.getPlaces, this.locationErrorHandler, options);
    } else {
        alert("Sorry, browser does not support geolocation!");
    }
}

推荐阅读