【发布时间】:2021-11-28 20:41:09
【问题描述】:
import React,{ useState, useEffect } from 'react'
import axios from 'axios'
const App = () => {
const [ countries, setCountries ] = useState([])
const [ search, setSearch ] = useState('')
const [ weather, setWeather ] = useState({})
const [ capital, setCapital ] = useState('')
const api_key = process.env.REACT_APP_API_KEY
const searchedCountries = countries.filter(country =>
country.name.common.toLowerCase().includes(search.toLowerCase()))
useEffect(() => {
axios
.get('https://restcountries.com/v3.1/all')
.then( response => {
setCountries(response.data)
})
},[])
useEffect(() => {
const url = `http://api.weatherstack.com/current?access_key=${api_key}&query=${capital}`
axios
.get(url)
.then(response => {
setWeather(response.data)
console.log('logged weather', response.data)
console.log('capital inside: ', capital)
})
},[search])
console.log(searchedCountries)
const handleSearch = (event) => {
setSearch(event.target.value)
if(searchedCountries.length === 1){
setCapital(searchedCountries[0].capital[0])
console.log('capital is set', capital)
}
else
setCapital('')
}
const handleShow = (event) => {
event.preventDefault()
setSearch(event.target.value)
}
if(searchedCountries.length > 10){
return(
<>
<div>
find countries
<input value = {search} onChange = {handleSearch} />
</div>
<p>Too many matches, specify another filter</p>
</>
)
}else{
if(searchedCountries.length === 1){
const languages = Object.keys(searchedCountries[0].languages)
console.log(typeof weather, weather)
return(
<>
<div>
find countries
<input value = {search} onChange = {handleSearch} />
</div>
<h1>{searchedCountries[0].name.common}</h1>
<p>capital {searchedCountries[0].capital[0]}</p>
<p>population {searchedCountries[0].population}</p>
<h2>languages</h2>
<ul>
{languages.map(language =>
<li key = {language}>{searchedCountries[0].languages[language]}</li>)}
</ul>
<img src= {searchedCountries[0].flags.png} alt= 'flag' />
<h2>Weather in {searchedCountries[0].capital[0]}</h2>
{/* <p><strong>temperature: </strong> {weather.current.temperature} Celcius</p> */}
</>
)
}else{
return(
<>
<div>
find countries
<input value = {search} onChange = {handleSearch} />
</div>
{searchedCountries.map( (country, index) => {
return(
<div key = {country.name.official}>{country.name.common}
<button onClick = {handleShow} value = {country.name.common} >show</button>
</div>
)
})}
</>
)
}
}
}
export default App
例如: 我输入了“fin”, 对象仍然是空的。 输入“finl”后, 天气变量包含赫尔辛基的天气数据。(我的每月使用量已达到极限,为什么示例图片的weather.success值为false。
如果我在我的代码中取消注释注释行,应用程序会在您输入“fin”后崩溃。
我想在这个应用程序中使用天气 API 中的数据而不会遇到错误。
你能帮我解决这个问题吗? 我是一名初学者,正在学习 React,以及 React 与 API 的交互。
感谢您的理解。
【问题讨论】:
标签: javascript node.js reactjs api axios