javascript - 无法访问 React Component 中的 Javascript 对象

标签 javascript arrays json reactjs

所以,我陷入了 React,它已经让我挠头了..

我正在抓取一些 API 数据并尝试访问任何特定索引或循环 - 无论我做什么,它似乎都不起作用!

这里是主要组件:

class App extends React.Component {
const CityListNames = ['Peterborough', 'Manchester', 'Brighton', 'Liverpool', 'Cardiff'];

  constructor(props) {

    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };

  }

  // Fire our function below on app load
  componentDidMount() {
    this.getWeather();
  }

  // getWeather - make api call
  getWeather = () => {

    let results = [];

    // Loop through our cities list here to gather data 
    // We will then push this into this.state.results
    CityListNames.forEach(function (name) {

      let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;
      let data;

      // get api data  
      fetch(api_url)
      .then(res => res.json())
      .then(
        (result) => {
          results.push(result); 
          console.log(result[0]);   
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );    

    });    

    this.setState({
      isLoaded: true,
      items: results
    }); 



  }  

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="weather-app">

        </div>
      );
    }  
  }
}

export default App;

当我使用 console.log(result[0]); 时,它只是在控制台中输出为“undefined”。

我正在尝试将所有值分配给结果变量,然后将其推送到状态。

当我执行 console.log(items) 时,它也会显示所有项目,这很奇怪。

API 数据

enter image description here

任何帮助将不胜感激!

谢谢

最佳答案

在设置状态之前,您必须等待所有 api 请求解决,因此不要使用 forEach,而是使用 map,然后像这样返回日期 promise :

getWeather = () => {

    // Loop through our cities list here to gather data 
    // We will then push this into this.state.results
    Promise.all(CityListNames.map(function (name) {

      let api_url = "http://api.openweathermap.org/data/2.5/weather?q="+name+",UK&appid="+ApiKey;

      return fetch(api_url)
      .then(res => res.json());

    })).then((results) => {
      this.setState({
        isLoaded: true,
        items: results
      }); 
    }).catch((error) => {
      this.setState({
        isLoaded: true,
        error
      });
    });
  }  

关于javascript - 无法访问 React Component 中的 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382540/

相关文章:

php - 多维数组按值排序,同时将其转换为整数

java - 如何在Java中创建缓存来存储用户 session

javascript - 如何在 javascript-vuejs 中将两个函数的总和放入数组中

javascript - 在控制台中获取表 td 的内容

javascript - 调用promise API时如何有效地聚合数组?

javascript - Jquery:试图在悬停时隐藏和显示具有相同 ID 和编号的多个 div

带参数的 Javascript "class"扩展?

python - 使用 python 的 long 类型的 numpy 数组

c# - 在 C# 中反序列化 JSON 数组

php - 从 PHP 数组到 Javascript 数组大括号与方括号