繁体   English   中英

React: Uncaught TypeError: Cannot read properties of undefined (reading 'setState')

[英]React: Uncaught TypeError: Cannot read properties of undefined (reading 'setState')

我是学习 React 的新手,我想通过 API 调用来获取一些东西,这似乎对我不起作用。 对于以下代码,我在标题中提到的控制台中遇到错误。

该错误显示在以下代码的 fetch 语句中,我无法纠正它。 我在这里所做的是获取 position 的纬度和经度并将其传递给 URL 以获取天气。

从“反应”导入反应,{组件}

class WeatherData extends Component{
  constructor(props){
    super(props);
    this.state ={
      weatherReport:[]
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(function(position) {
      const lat =  position.coords.latitude;
      const lon = position.coords.longitude;
    fetch('https://api.openweathermap.org/data/2.5/weather?lat='+{lat}+'&lon='+{lon}+'&appid=xxxxxxxxxxxxxxxxxxxxxxx')
    .then(response => response.json())
    .then(data => this.setState({ weatherReport: data.main}));
    });
    
}
  render(){
    const  { weatherReport }  = this.state;

    
    return(
      <div>
          {weatherReport.temp}
      </div>
    );
  }
}

export default WeatherData;

任何帮助将不胜感激。

You are using a function using the function keyword when getting the geolocation - this gives a new this reference to anything inside its scope, including the arrow function and its contents. 使用粗箭头 function 将当前this绑定到其子块,以在使用回调时保持正确的 scope。

此外,不知道你为什么在 url 中链接 object 像这样:

componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => { // this line
        const lat = position.coords.latitude;
        const lon = position.coords.longitude;
        fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=xxxxxxxxxxxxxxxxxxxxxxx`
          .then(response => response.json())
          .then(data => this.setState({
            weatherReport: data.main
          }));
        });
    }

这是由于使用function关键字和“胖箭头”语法 ( => ) 之间的差异

function关键字创建了一个新的“ this上下文”,而粗箭头继承了父上下文。 换句话说,当您使用function时, this关键字的值在 function 内部变成了新的值,而使用=>时,它与在 ZC1C425268E68385F1ABZA4 外部的值相同。

您可以在此处阅读有关this关键字的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

更多关于function=>之间的区别可以在这里找到:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions


所以,而不是这样写:
getCurrentPosition(function(position) {

你应该这样写:
getCurrentPosition((position) => {

完整示例:

import React, { Component } from "react"

class WeatherData extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weatherReport: []
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => { // <- this is what has changed
      const lat = position.coords.latitude;
      const lon = position.coords.longitude;
      fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + { lat } + '&lon=' + { lon } + '&appid=xxxxxxxxxxxxxxxxxxxxxxx')
        .then(response => response.json())
        .then(data => this.setState({ weatherReport: data.main }));
    });
  }

  render() {
    const { weatherReport } = this.state;

    return (
      <div>
        {weatherReport.temp}
      </div>
    );
  }
}

export default WeatherData;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM