【发布时间】:2019-12-17 03:24:43
【问题描述】:
我目前正在学习 react-native 一段时间后,我遇到了一个我不明白的奇怪事件。
我正在从 API 获取 JSON 文件并将其保存在我的状态中。当我尝试使用点和括号表示法访问值时,文件中的其他地方会破坏我的代码“未定义不是对象”,并且该常量的值确实未定义。但奇怪的是,如果我在我的 fetch 和点/括号符号中使用 setState 来获得一个特定的值,它就可以正常工作。但我想拥有这个功能,而我将通过数据进行很多映射。
我读到我可能需要使用 JSON.parse,但可以确定在我的 fetch 中放置它的位置,它在 console.log 中返回了一个错误。
JSON.stringify 有效,但我只有一个巨大的字符串,所以失去了对象的力量。
点和括号表示法尝试了这一切,正如我所说的在 fetch 中完美工作,但是在调用状态时
先将 state 设置为 const,然后将其传递到 console.log,没有区别。
fetchWeather(lat = 15, lon = 85) {
fetch(
`http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&APPID&APPID=${API_KEY}&units=metric`,
)
.then(res => res.json())
.then(json => {
this.setState({
forecast: json.list,
temp: json.list[0].main.temp // WORKS! returns temp eg 25.34
isLoading: false,
});
})
.catch(error => console.log(error));
}
console.log(this.state.forecast[0]); //works I get the first index of an array of objects but has and added key Object {}
console.log(this.state.forecast[0].main.temp); //undefined
console.log(this.state.forecast[0]['main']['temp']); //undefined
我看到这个 Object {} 出现在控制台中,但也许这没什么好担心的?
例如。
"main": Object {
"grnd_level": 1008.34,
"humidity": 54,
"pressure": 1013.04,
"sea_level": 1013.04,
"temp": 28.1,
"temp_kf": 4.74,
"temp_max": 28.1,
"temp_min": 23.36,
},
应该是,
"main": {
"grnd_level": 1008.34,
"humidity": 54,
"pressure": 1013.04,
"sea_level": 1013.04,
"temp": 28.1,
"temp_kf": 4.74,
"temp_max": 28.1,
"temp_min": 23.36,
},
我希望 console.log(this.state.forecast[0].main.temp) 返回 23.45 和
console.log(this.state.forecast[0]['main'])return
"grnd_level": 1008.34,
"humidity": 54,
"pressure": 1013.04,
"sea_level": 1013.04,
"temp": 28.1,
"temp_kf": 4.74,
"temp_max": 28.1,
"temp_min": 23.36,
【问题讨论】:
-
从您的问题和要点来看,我并不清楚您在哪里尝试访问您的状态并遇到错误 - 但是,请注意
setStateenqueues 变化。不要尝试在调用setState后立即访问这些字段。setState接受回调作为您可以使用的第二个参数。 -
将对象存储在我的状态中作为预测是很奇怪的,然后当我在我的渲染方法中放置一个 console.log 时,无法使用点或括号表示法访问键和值。好像它不是一个对象?您将如何从对象访问“temp”?
-
请注意,此条件的计算结果始终为
true,并且即使在状态被正确填充之前,console.log也会被尝试:if (this.state.forecast !== {}) {- 如果它在此console.log中中断,那么这是原因。 -
我已将此作为答案添加,如果我的假设正确,请接受。
标签: javascript json reactjs fetch native