保存在clima变量中的API响应显示未定义,但是当我使用控制台日志时,它显示在response.data中,而不是clima中,我需要一些json格式吗?使用WheaterStack API
import React,{useEffect,useState} from 'react'
import axios from 'axios'
const Clima=(ciudad)=>{
const [clima,setClima]=useState([])
const api_key = process.env.REACT_APP_API_KEY
useEffect(()=>{
//if(ciudad === undefined)
// return
// console.log(ciudad,'ciudadddddddds')
axios
.get(`http://api.weatherstack.com/current?access_key=${api_key}&query=${ciudad.city}`)
.then(response =>{
setClima(response.data)
console.log(response.data)
console.log(clima)
}
)
},[api_key,ciudad])
return(
<div></div>
)
}
export default Clima
答案 0 :(得分:0)
看着问题中提供的沙箱,我看到此错误:
xhr.js:184 Mixed Content: The page at 'https://codesandbox.io/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://api.weatherstack.com/current?access_key=undefined&query=New+York'. This request has been blocked; the content must be served over HTTPS.
dispatchXhrRequest @ xhr.js:184
xhrAdapter @ xhr.js:13
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:76
wrap @ bind.js:9
eval @ App.js? [sm]:14
commitHookEffectListMount @ react-dom.development.js:19731
commitPassiveHookEffects @ react-dom.development.js:19769
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
flushPassiveEffectsImpl @ react-dom.development.js:22853
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
flushPassiveEffects @ react-dom.development.js:22820
eval @ react-dom.development.js:22699
workLoop @ scheduler.development.js:597
flushWork @ scheduler.development.js:552
performWorkUntilDeadline @ scheduler.development.js:164
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:91)
看起来好像get:您设置的必须是https而不是http请求。由于不检查响应,因此仅调用setClima可能是问题所在吗?即setClima没有被加载,或者以某种方式不能满足您的要求?
我真的不相信这可以解决问题,因为从某种意义上来说,您正在检查响应,并且似乎包含您认为可以的数据,因此某些工作正常。但是,可能值得将get:设置为https而不是http来查看是否有任何更改。
(此答案更多地是在评论中进行讨论,但是错误太大而无法在评论中添加,因此我创建了此“答案”。)
编辑:我认为使用沙箱存在问题-使用https调用它,因此get:http被拒绝。这不是现实生活中的问题,但这确实意味着沙箱无法用于帮助调试。
答案 1 :(得分:0)
因此,似乎从未设置clima
的值,但实际上控制台日志从未与更新的数据一起发生。 setClima
不会立即更改变量值,而是会触发更新,告知React需要重新渲染组件。
axios
.get(`http://api.weatherstack.com/current?access_key=${api_key}&query=${ciudad.city}`)
.then(response =>{
setClima(response.data) // set state and queues update
console.log(response.data)
console.log(clima) // logs what clima is on this render
})
为了读取clima的值,应将控制台日志放置在useEffect
调用之外。
const [clima, setClima] = useState([]);
console.log(clima); // will be [] on first call, and the response data on second call
useEffect(()=>{
axios
.get(`http://api.weatherstack.com/current?access_key=${api_key}&query=${ciudad.city}`)
.then(response =>{
setClima(response.data)
})
},[api_key,ciudad])
该日志将发生两次,一次是使用初始状态值([]
),一次是使用组件更新时的响应数据。