Javascript 如何使用get方法从response.data中提取道具

Javascript 如何使用get方法从response.data中提取道具,javascript,reactjs,api,axios,Javascript,Reactjs,Api,Axios,我试图从这个api返回道具名称,但控制台只返回未定义的道具名称。有人能帮我吗 useEffect(() => { if(selectedCountry === '0'){ return } axios.get<Country>(`https://restcountries.eu/rest/v2/name/france`).then(response => { const {name} = response.data

我试图从这个api返回道具名称,但控制台只返回未定义的道具名称。有人能帮我吗

  useEffect(() => {
    if(selectedCountry === '0'){
      return
    }
    axios.get<Country>(`https://restcountries.eu/rest/v2/name/france`).then(response => {
      const {name}  = response.data
      console.log(name)
    })
  })
useffect(()=>{
如果(selectedCountry==“0”){
返回
}
axios.get(`https://restcountries.eu/rest/v2/name/france`)。然后(响应=>{
const{name}=response.data
console.log(名称)
})
})

来自GET请求的响应是一个数组:

[
{
“名称”:“法国”,
...
}
]
由于返回的响应是一个数组,因此需要对第一项进行索引

useEffect(() => {
  if (selectedCountry === '0') {
    return 
  } 
  axios.get('https://restcountries.eu/rest/v2/name/france')
    .then(response => {
      const { name } = response.data[0] 
      console.log(name) 
    })
})


将来,您可以先尝试打印整个响应,以确保了解数据的形状。

由于从服务返回的数据是一个数组,因此您应该读取响应的名称。数据[0]

useffect(()=>{
如果(selectedCountry==“0”){
返回
} 
axios.get(`https://restcountries.eu/rest/v2/name/france`)。然后(响应=>{
const{name}=response.data[0]
console.log(名称)
})
},[])

观察返回的数据,响应数据是一个数组而不是一个对象

[{"name":"France","topLevelDomain":[".fr"],"alpha2Code":"FR","alpha3Code":"FRA","callingCodes":["33"],"capital":"Paris","altSpellings":["FR","French Republic","République française"],"region":"Europe","subregion":"Western Europe","population":66710000,"latlng":[46.0,2.0],"demonym":"French","area":640679.0,"gini":32.7,"timezones":["UTC-10:00","UTC-09:30","UTC-09:00","UTC-08:00","UTC-04:00","UTC-03:00","UTC+01:00","UTC+03:00","UTC+04:00","UTC+05:00","UTC+11:00","UTC+12:00"],"borders":["AND","BEL","DEU","ITA","LUX","MCO","ESP","CHE"],"nativeName":"France","numericCode":"250","currencies":[{"code":"EUR","name":"Euro","symbol":"€"}],"languages":[{"iso639_1":"fr","iso639_2":"fra","name":"French","nativeName":"français"}],"translations":{"de":"Frankreich","es":"Francia","fr":"France","ja":"フランス","it":"Francia","br":"França","pt":"França","nl":"Frankrijk","hr":"Francuska","fa":"فرانسه"},"flag":"https://restcountries.eu/data/fra.svg","regionalBlocs":[{"acronym":"EU","name":"European Union","otherAcronyms":[],"otherNames":[]}],"cioc":"FRA"}]
因此,您应该将响应数据视为一个数组,如下所示

axios.get('https://restcountries.eu/rest/v2/name/france').
    then(response => {
        console.log(response)
        const [extractedData]  = response.data //response.data is an array, and you extract the content to extractedData
        const {name, topLevelDomain}= extractedData //extractedData is an object, so you can use braces to visit fields with their name 
        console.log(data)
        console.log(name)
        console.log(topLevelDomain)
    })