通过插值从API获取数据来搜索某个城市的天气



我正在尝试从API获取天气数据,当在不使用插值获取(https://weatherapi-com.p.rapidapi.com/forecast.json?q=London&days=3(的情况下获取数据时,它可以正常工作。但当我使用下面的代码并在搜索新城市后按enter键时,我会收到错误消息";错误的请求";缺少参数q。任何帮助都将不胜感激!如果我能以任何方式帮助澄清,请告诉我。

import React from "react"
// import WeatherDisplay from "./WeatherDisplay";
import { useState, useEffect } from "react"
import { scryRenderedComponentsWithType } from "react-dom/test-utils";
import Item from "./Item"
function SearchBar() {
const [ defaultWeather, setDefaultWeather ] = useState([])
const [ searchedCity, setSearchedCity ] = useState('London') 
const [ isLoaded, setIsLoaded ] = useState(false)
const [didMount, setDidMount] = useState(false); 
const [ input, setInput ] = useState('')

const searchWeather = () => {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'weatherapi-com.p.rapidapi.com',
'X-RapidAPI-Key': 'de51889a1fmshe095099b1a97993p13134fjsnc818ad7373cb'
}
};

fetch(`https://weatherapi-com.p.rapidapi.com/forecast.json?q=${searchedCity}&days=3`, options)
.then(response => response.json())
.then((data) => {
console.log(data)
setDefaultWeather(data)
setIsLoaded(true)
})
.catch(err => console.error(err));
}
useEffect(() => {
searchWeather()

}, [searchedCity])


function handleSubmit(e) {
e.preventDefault()
setSearchedCity(input)
}    
if (!isLoaded) return  <h3>Loading...</h3>;

return (
<div>
<form 
className="search-form"
onSubmit={handleSubmit}
>
<label>Search</label>
<input 
text="text" 
id="search"

onChange={e => setSearchedCity(e.target.value)}
/>
{/* <button>Submit</button> */}
<div className="display">
</div>
</form>
</div>
)    
}

export default SearchBar;

onChange={(e(=>setInput(e.target.value(}而不是onChange={e=>setSearchedCity(e.target.value(}

我不明白为什么你在提交和更改时都设置setSearchedCity,但在你的使用效果中,至少你可以添加条件为:

useEffect(() => {
if (searchedCity) searchWeather()        
}, [SearchedCity])

最新更新