初学者天气 API 问题

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

谁能告诉我这段代码哪里出了问题?触发一次,并且始终显示相同的城镇名称。

const Weather = () => {

    const [zipCode, setZipCode] = useState("");
    const [weather, setWeather] = useState(null);
    const [error, setError] = useState(null);


    const url = "https://api.openweathermap.org/data/2.5/weather?zip=36578,us&units=imperial&appid=da2f2d11af56e955015eed08e226b806";

    const apiKey = "...";


    const getWeatherData = async () => {
        try {
            const response = await axios.get(url, {
              
            });
            setWeather(response.data)
            setError(null)
            console.log(response.data)
        } catch (error) {
            setError("Error while fetching weather details")
        }

    }

    const handleChange = (e) => {
        setZipCode(e.target.value)
    };

    const handleClick = () => {
        getWeatherData();
    };

    return (
        <>
            <div className="weather-container">
                <h1 className="weather-header">Weather App</h1>
                <div className="weather-form">
                    <input
                        placeholder="Enter Zip"
                        name={zipCode}
                        onChange={(e) => { handleChange(e) }}
                        value={zipCode}
                    />
                    <button onClick={() => { handleClick() }}> Get Weather </button>
                </div>

                {error !=null && (<p className="error-message">{error}</p>)}
                {
                    weather != null && (
                        <div className="weather-info">
                            <h2>Name : {weather.name}</h2>
                            <p>Temperature : {weather.main.temp}°F</p>
                            <p>Description : {weather.weather[0].description}</p>
                        </div>
                    )
                }

            </div>
        </>
    );
};
export default Weather

我尝试更改输入值以不同方式显示。我不确定为什么它不更新。

reactjs jsx
1个回答
0
投票

您有几个问题:

您的

url
变量具有硬编码的邮政编码
36578
。一个简单的解决方法是在 getWeatherData 函数中声明 url 变量:

const getWeatherData = async () => {        
    const url = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},us&units=imperial&appid=da2f2d11af56e955015eed08e226b806`
    try {
            const response = await axios.get(url, {
              
            });
            setWeather(response.data)
            setError(null)
            console.log(response.data)
        } catch (error) {
            setError("Error while fetching weather details")
        }
    
    }

此外,您暴露了您的 api 密钥,您需要重新生成它,这样互联网上的每个人都不会使用它!

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