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

问题描述 投票:0回答:2

我正在尝试从 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;
javascript reactjs database interpolation fetch-api
2个回答
1
投票

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


0
投票

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

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

  
© www.soinside.com 2019 - 2024. All rights reserved.