Установка состояния приводит к TypeError: это не определено - PullRequest
0 голосов
/ 22 июня 2019

У меня есть следующая ошибка в строке 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')
)

Ответы [ 2 ]

0 голосов
/ 22 июня 2019

Вам нужно связать свои внутренние функции в конструкторе. Обновите ваш код конструктора следующим образом:

constructor(props) {
    super(props);
    this.state = {
        showNoResultsMessage: false 
    }
    this.getPlaces = this.getPlaces.bind(this);
    this.locationErrorHandler = this.locationErrorHandler.bind(this);
    this.getLocation = this.getLocation.bind(this);
}

Я также заметил, что вы устанавливаете состояние в функции, но не инициализируете ее. Добавили состояние тоже в конструктор. Вы можете изменить его значение согласно вашему требованию.

0 голосов
/ 22 июня 2019

Вы должны связать функции в своем конструкторе следующим образом:

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!");
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...