【发布时间】:2019-11-05 14:06:30
【问题描述】:
我正在使用 React Native 和 Open Weather Map API 构建一个小型天气应用程序。我从 API 调用中检索到的数据比我想要使用的要多,所以我只解析出我需要的部分并将它们存储在一个数组中。然后我将数组设置为状态对象。我可以引用该对象,但不是说我的数组是一个数组,而是说它是一个对象,因此不会让我在其上使用任何数组方法。我该如何解决这个问题?
//reponseData is the data retrieved from the API call; the data retrieved is an object with arrays and objects
within. The forecast data for the next five days is given in 3 hour increments, so you have a 40 item array of
data pieces. I loop through this list of 40 items, pull out just what I need...
let forecastArray = [];
for (let i=0; i<responseData.list.length; i++) {
let day = responseData.list[i].date
let high = responseData.list[i].weather[0].hiTemp
let low = responseData.list[i].weather[0].loTemp
let condition = responseData.list[i].sys.condition
forecastArray.push(day)
forecastArray.push(high)
forecastArray.push(low)
forecastArray.push(condition)
this.setState({
forecastData: forecastArray
})
当我登录时,我得到一个数组....
console.warn("forecast is: ", this.state.forecastData)
OUTPUTS: forecast is: ["11-06-2019", 52.5, 47.3, "sunny", "11-06-2019", 63.9, 39.7, "sunny", ...]
例如,引用 this.state.forecastData[2] 却给了我错误。所以我检查了 this.state.forecast 的类型,看看为什么,它说数组是一个对象?我需要进一步划分数组数据并对其进行操作。前几个项目(例如 forecastData[0] 到 forecastData[9] 将用于 2019 年 6 月 11 日下午 3 点、下午 6 点、晚上 9 点的预报天气,所以我需要拉出这些项目,获得最高点和最低点,等等。我不能这样做,因为我什至无法引用数组中的项目。
我尝试过的事情: 使用 Object.entries 和 Object.assign 方法,但这只是将项目拆分为几个数组,第一项是位置编号,第二项是数组项内容。我已经尝试在使用它的组件中操作数组,但它仍然是一个对象而不是数组,所以我不能引用单个项目。数据集足够大,我认为将 40 多个项目中的每一个都推送到它们自己的状态对象键中并不是最佳做法。
【问题讨论】:
标签: arrays object react-native-android