You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中基于OpenWeatherAPI数据的消息不更新问题求助

React中根据OpenWeatherAPI数据更新提示消息失败的解决方法

问题描述

我在React项目中尝试根据OpenWeatherAPI返回的当前天气数据,结合温度和天气描述展示对应的穿搭提示消息,但数据传入后消息无法更新,初始的useState默认消息可以正常显示。

相关代码

Aside.js文件代码

//Aside Component - used for suggesting things to wear based on the location

//DEPENCENCIES
import React, { useState } from 'react'


function Aside() {
    /* PSUEDOCODE:

    TRYING TO USE THE DATA BEING PULLED IN AND BASED ON THE DATA, THERE'S A DIFFERENT MESSAGE BASED ON THE WEATHER AND THE DESCRIPTION

        dependencies - import WeatherCard and WeatherApp so I can use the values in the WeatherCard & WeatherApp for my algorithm
    
        useState - to set the initial value of the aside. say something like, "type zipcode to get suggestions for attire"

        setMessage - to grab the information on what to say when the zip code is displayed

        ex) const setMessage = async () => {
            use if/else statements to choose which message to display. use emojis!
                an if/else statement for weather[0].description
                an if/else statement for main.temp
                an if/else statement for main.humidity
            nest all of the if/else statements in a trycatch, so if it doesn't work, it sends an error message


        useEffect - use useEffect to run the setMessage function
        ex)
        useEffect(() => {

        
        , []}) <--- This is where I put the zipcode to indicate that it wont run unless the zipcode has a value

        const display - to display the message

        return - returning the const display
    
    */


    let [message, setMessage] = useState("Type in ZipCode to get suggestions for attire!")

    /* COMMENTED OUT TO KEEP THE SITE FROM CRASHING. FINISH CODING THIS LATER
    const { zipCode } = useParams()*/

    setMessage = ({ WeatherData }) => {
        try {
            //MESSAGES FOR TEMPERATURE
            if (WeatherData.main.temp > 100) {
                message = "It's hot.... like really hot... leathers not recommended at all..."
            } else if(WeatherData.main.temp < 70) {
                message = "it's warm today! No need for bundling up"
            } else if(WeatherData.main.temp < 45) {
                message = "It's not that cold outside today, but a small sweater will do"
            } else if(WeatherData.main.temp < 20) {
                message = "Brrr, chilly! try putting on a Jacket!"
            } else {
                message = ""
            }

            //MESSAGES FOR DESCRIPTION - tell the users what to bring/buy
            if (WeatherData.weather[0].description == "clear sky") {
                message = "You might want to get some sunglasses"
            } else if (WeatherData.weather[0].description == "shower rain") {
                message = "Make sure you have an umbrella"
            } else if (WeatherData.weather[0].description == "rain" && WeatherData.weather[0].description == "thunderstorm") {
                message = "Grab an umbrella! It's pouring!"
            } else if (WeatherData.weather[0].description == "snow") {
                message = "get your snowboots 'cause its snowin outside."
            } else {
                message =""
            }

        } catch (error) {
            message = "No zipcode, no attire suggestions. sorry..."
        }
    }

    
    /* COMMENTED OUT TO KEEP THE SITE FROM CRASHING. FINISH CODING THIS LATER
    useEffect(() => {
        setMessage()
    }, [zipCode])*/

    return (
        <div className='asideContainer'>
            {message}
        </div>
    )
}




export default Aside

App.js中组件引入代码

<Aside zipCode={zipCode} weatherData={weatherData} />

解决步骤及修复代码

问题分析

  1. 未接收父组件传入的zipCode和weatherData props,组件无法获取外部数据。
  2. 重写了useState返回的setMessage方法,破坏了React的状态更新机制。
  3. 直接修改message变量不会触发组件重渲染,必须使用setMessage函数更新状态。
  4. 温度判断逻辑顺序错误,导致部分条件永远不会触发。
  5. 天气描述的逻辑错误(&&判断同一变量等于两个不同值),且会覆盖温度消息。
  6. 缺少监听props变化的useEffect,数据更新时不会重新生成消息。

修复后的Aside.js代码

//Aside Component - used for suggesting things to wear based on the location
import React, { useState, useEffect } from 'react'

function Aside({ zipCode, weatherData }) { // 接收父组件传入的props
    const [message, setMessage] = useState("Type in ZipCode to get suggestions for attire!")

    // 自定义生成消息的函数,不覆盖setMessage
    const generateMessage = () => {
        try {
            if (!weatherData || !weatherData.main || !weatherData.weather) {
                setMessage("No zipcode, no attire suggestions. sorry...")
                return
            }

            let tempMessage = ""
            const temp = weatherData.main.temp
            const description = weatherData.weather[0].description

            // 温度消息(从高到低排序,避免逻辑覆盖)
            if (temp > 100) {
                tempMessage = "It's hot.... like really hot... leather's not recommended at all... "
            } else if (temp < 20) {
                tempMessage = "Brrr, chilly! Try putting on a Jacket! "
            } else if (temp < 45) {
                tempMessage = "It's not that cold outside today, but a small sweater will do "
            } else if (temp < 70) {
                tempMessage = "It's warm today! No need for bundling up "
            }

            // 天气描述消息,追加到温度消息后
            if (description === "clear sky") {
                tempMessage += "You might want to get some sunglasses"
            } else if (description === "shower rain" || description === "rain") {
                tempMessage += "Make sure you have an umbrella"
            } else if (description === "thunderstorm") {
                tempMessage += "Grab an umbrella! It's pouring and thundering!"
            } else if (description === "snow") {
                tempMessage += "Get your snowboots 'cause it's snowin' outside."
            }

            setMessage(tempMessage || "Enjoy your day!")
        } catch (error) {
            setMessage("No zipcode, no attire suggestions. sorry...")
        }
    }

    // 监听zipCode和weatherData变化,更新消息
    useEffect(() => {
        if (zipCode && weatherData) {
            generateMessage()
        } else {
            setMessage("Type in ZipCode to get suggestions for attire!")
        }
    }, [zipCode, weatherData]) // 依赖数组:当这两个值变化时重新执行

    return (
        <div className='asideContainer'>
            {message}
        </div>
    )
}

export default Aside

关键修复点说明

  • 接收props:在组件参数中解构zipCode和weatherData,获取父组件传入的数据。
  • 状态更新:使用useState返回的setMessage函数更新状态,确保组件重渲染。
  • 逻辑顺序:温度判断从极端值开始(最高/最低),避免条件被提前覆盖。
  • 消息合并:将温度和天气描述的消息合并,避免互相覆盖。
  • useEffect监听:依赖数组中加入zipCode和weatherData,当数据更新时自动重新生成消息。
  • 数据校验:增加对weatherData的存在性校验,避免空值报错。

内容的提问来源于stack exchange,提问作者Mary Oreofejesu Imarenezor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:24:55