从 api 中获取数据并进行插值以搜索某个城市的天气

Fetching data from an api with interpolation to search weather in a certain city

我正在尝试从 api 获取天气数据,当在不使用插值 fetch(https://weatherapi-com.p.rapidapi.com/forecast.json?q=London&days=3) 的情况下获取数据时,它工作正常。但是当我使用下面的代码并在搜索新城市后按回车键时,我收到错误消息“Bad request”Parameter q is missing。任何帮助,将不胜感激!如果我能以任何方式帮助澄清,请告诉我。

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;

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

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

  

onChange={(e) => setInput(e.target.value)} 代替 onChange={e => setSearchedCity(e.target.value)}