React api 调用返回 [object Object] [object Response] 或 [object Promise]

jnr0790

我正在使用开放的天气地图 API 制作一个非常简单的天气应用程序。我得到的唯一响应是 axios 调用时的 [object Object],使用 fetch 时的 [object Response],控制台日志 res.json() 时的 [object Promise]。我在控制台中收到一条成功的 GET 消息。我现在很困。

如何使用应该返回的天气访问对象?

任何帮助表示赞赏。

const Weather = (props) => {

const [weather, setWeather] = useState({})
const [location, setLocation] = useState('')

const handleChange = event => {
 event.persist()

 setLocation(prevLocation => {
   // console.log(`previous ${prevLocation}`)
   // console.log(`target ${event.target.value}`)
   const updatedInput = { [event.target.name]: event.target.value }
   // console.log(`updated ${updatedInput}`)
   const createdLocation = Object.assign({}, prevLocation, updatedInput)
   // console.log(`created location ${createdLocation.toString()}`)
   return createdLocation.location
 })
}

console.log(`LOCATION = ${location}`)

const handleSubmit = (event) => {
 event.preventDefault()
 fetch(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${apiKey}`)
   .then(res => {
     console.log(`RES = ${res.json()}`)
   })
   .catch(console.error)
}

另外,如果有更好的方法来问这个问题,我也会做一些笔记。

韦伯

您得到了正确的响应,您只需要使用对象属性来访问数据。尝试:

fetch(`https://api.openweathermap.org/data/2.5/weather? 
  q=${location}&appid=${apiKey}`)
  .then(res => res.json())
  .then(data=>setWeather(data.weather.main)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章