【问题标题】:json file push the STATEjson 文件推送状态
【发布时间】:2019-11-06 11:11:36
【问题描述】:

我创建了带有反应的基本天气应用程序,我想将所有 json 文件推送状态,但我不能这样做。

import React, {Component} from 'react';
import './App.css';
import CityList from './CityList';
// this is an array that just has id, city_name and country property
import {cityName} from './Resorces';

class App extends Component {
  constructor (){
    super()
    this.state = {
      cities:{},
    }
  }

  render() {
    const {cities} = this.state;
    console.log('cities state', cities);

    return (
      <div className='tc'>
        <h1 className='f1  pa3 ma2'> World Weather</h1><hr/>
        <CityList cities={cities}/>
      </div>
    );
  }
 componentDidMount(){
  const citySource = cityName.map((city) => {
    return fetch(https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d)
      }).then(response => response.json())
       .then( data => {this.setState({cities : data})});
    console.log('citySource', citySource);
  }
}
export default App;

上面的这段代码没有访问 Resorces.js 中的 cityName 数组,也没有执行 map() 循环,因此没有将 json 文件推送到 STATE 中的对象的城市

我该怎么做?

下面是cityName数组

export const cityName = [
  {
    id: 1,
    name: "New York City",
    country: "US",
  },
  {
    id: 2,
    name: "Vienna",
    country: "AT",
  },
  {
    id: 3,
    name: "Istanbul",
    country: "TR",
  },
  {
    id: 4,
    name: "London",
    country: "GB",
  },
  {
    id: 5,
    name: "Ankara",
    country: "TR",
  },
  {
    id: 6,
    name: "Paris",
    country: "FR",
  },
  {
    id: 7,
    name: "Madrid",
    country: "ES",
  },
  {
    id: 8,
    name: "Amsterdam",
    country: "NL",
  },
  {
    id: 9,
    name: "Belgrade",
    country: "RS",
  },
  {
    id: 10,
    name: "Munich",
    country: "DE",
  },
  {
    id: 11,
    name: "Berlin",
    country: "DE",
  },
  {
    id: 12,
    name: "Chicago",
    country: "US",
  },
  {
    id: 13,
    name: "Brussels",
    country: "BE",
  },
  {
    id: 14,
    name: "Rome",
    country: "IT",
  },
  {
    id: 15,
    name: "Washington",
    country: "US",
  }
];

【问题讨论】:

  • 能否在问题中添加cityName示例数据
  • 如果它不是一个数组,所以 map 不起作用,array.map 是您可以在 mdn developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 上阅读更多信息的方法
  • @DILEEPTHOMAS 我现在肯定会做
  • 找出了问题并发布了答案检查,让我知道快乐的编码 :) 并欢迎使用 stackoverflow :)

标签: arrays reactjs api loops


【解决方案1】:

问题是你有一个数组,你需要用数组中的值调用一个api。

所以你需要使用Promise.all 包装它,检查下面的代码

编码愉快 :)

const cityName = [
  {
    id: 1,
    name: "New York City",
    country: "US",
  },
  {
    id: 2,
    name: "Vienna",
    country: "AT",
  },
  {
    id: 3,
    name: "Istanbul",
    country: "TR",
  },
  {
    id: 4,
    name: "London",
    country: "GB",
  },
  {
    id: 5,
    name: "Ankara",
    country: "TR",
  },
  {
    id: 6,
    name: "Paris",
    country: "FR",
  },
  {
    id: 7,
    name: "Madrid",
    country: "ES",
  },
  {
    id: 8,
    name: "Amsterdam",
    country: "NL",
  },
  {
    id: 9,
    name: "Belgrade",
    country: "RS",
  },
  {
    id: 10,
    name: "Munich",
    country: "DE",
  },
  {
    id: 11,
    name: "Berlin",
    country: "DE",
  },
  {
    id: 12,
    name: "Chicago",
    country: "US",
  },
  {
    id: 13,
    name: "Brussels",
    country: "BE",
  },
  {
    id: 14,
    name: "Rome",
    country: "IT",
  },
  {
    id: 15,
    name: "Washington",
    country: "US",
  }
];

let cities = []

Promise.all(cityName.map(city => 
  fetch(`https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)))
 .then(resp => Promise.all(resp.map(r => r.json())))
 .then(entireData => {
    cities = entireData
    console.log(cities)
}) // in react you need to do this.setState({cities: entireData})
 
 

【讨论】:

  • 感谢 DILEEP THOMAS ...它工作得很好...但请给我一些解释,因为我完全理解..你为什么使用 Promise?
  • 很高兴听到:),所以当你调用一个 api 时,问题是它的未来调用,所以你需要以某种方式让它等待,或者你需要一个回调,所以当我们用 promise 包装时。所有它将通过每一个执行,一旦所有呼叫完成,它将把数据放入城市。你可以在这里阅读更多内容,它会让你更好地了解这些 pblms stackoverflow.com/questions/46241827/…
【解决方案2】:

您遇到的具体错误是什么?

【讨论】:

  • 您可以在评论部分要求澄清,不要发布作为答案。
  • 我自然会得到这个错误```city.map 不是一个函数``` 因为城市是状态中的一个对象,但它是空的,因为我无法推送从 fetch() api 获取的数据
  • @GeorgePonta 是的,我能理解,即使我从 0 分开始。但是不要使用答案部分来澄清,因为很多人会提到解决方案。所以尝试解决并获得积分,试试看你会得到它:) 快乐编码。
【解决方案3】:

您是否首先收到回复?如果您收到回复,请执行此操作。

const citySource = cityName.map((city) => {
    return fetch(https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d)
      }).then(response => {
response.json()
this.setState({cities : response })
})
    console.log('citySource', citySource);
  }

【讨论】:

    【解决方案4】:

    在状态下用数组替换 citites 对象并替换此代码。

      componentDidMount() {
        const citySource = cityName.map((city) => {
            return fetch("https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d")
            .then(response => response.json())
            .then(data => { 
                this.setState(prevState => {
                    cities : [...prevState.cities , data]
                });
             });
            });
    }
    

    【讨论】:

    • 我收到此错误 ``` 应​​为赋值或函数调用,但看到一个表达式 no-unused-expressions ``
    • 我编辑了一个sn-p,你能再检查一下吗。
    猜你喜欢
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2021-04-13
    • 2015-05-09
    相关资源
    最近更新 更多