javascript - 在 useEffect 中调用时 Hook 未更新

标签 javascript reactjs react-hooks

我在从 API 检索数据后更新状态时遇到问题。 API 响应很好,但由于某种原因,我的 WeatherData-hook 没有更新并返回未定义。我做错了什么?

代码:

const renderForecastTable = ({ weatherData }) => (
    <table>
        <thead>
            <th>Tid</th><th>Temperatur</th><th>Vind</th><th>Nederbörd</th>
        </thead>
        <tbody>
        {
        weatherData.Map(hour => 
            <tr>
                <td>{hour.Time}</td><td>{hour.Temp}</td>
                <td>{hour.WindSpeed} m/s {hour.WindDirection} grader</td>
                <td>{hour.AvgPrecipitationIntensity} mm</td>
            </tr>)
            }
        </tbody>
    </table>
)

const Weather = (props) => {
    const [weatherData, setWeatherData] = useState([]);
    const [loading, setLoading] = useState(true);
    const location = useLocation();

    useEffect(() => {
        const getWeather = async () => {
            const response = await fetch(`weather`);
            const json = await response.json();
            setWeatherData(json);
            setLoading(false);
        }
        getWeather();
    }, [])

    return(
        loading ? <></> : renderForecastTable(weatherData)
    )
}

export default Weather;

JSON 响应:

[
  {"time":"4/9/2021 8:00:00 AM","temp":"6","windDirection":"216","windSpeed":"8.7","avgPrecipitationIntensity":"0"},
  {"time":"4/9/2021 9:00:00 AM","temp":"5.5","windDirection":"213","windSpeed":"7.9","avgPrecipitationIntensity":"0.2"},
  {"time":"4/9/2021 10:00:00 AM","temp":"4.7","windDirection":"218","windSpeed":"7.1","avgPrecipitationIntensity":"0.3"},
  {"time":"4/9/2021 11:00:00 AM","temp":"5.5","windDirection":"214","windSpeed":"7.3","avgPrecipitationIntensity":"0.3"},
  ...
]

最佳答案

renderForecastTable 使用一个参数并尝试解构 weatherData 属性,但它传递的是 weatherData 状态数组,renderForecastTable(天气数据)。看起来您也有一个拼写错误,weatherData.Map 可能应该是 weatherData.map,带有小写的“map”函数。由于 weatherData 被定义为一个数组,我假设您只是将其传递给 renderForecastTable 函数。

使用weatherData数组,不解构并修复“ map ”拼写错误。

const renderForecastTable = (weatherData) => (
    <table>
        <thead>
            <th>Tid</th><th>Temperatur</th><th>Vind</th><th>Nederbörd</th>
        </thead>
        <tbody>
        {
        weatherData.map(hour => 
            <tr>
                <td>{hour.Time}</td><td>{hour.Temp}</td>
                <td>{hour.WindSpeed} m/s {hour.WindDirection} grader</td>
                <td>{hour.AvgPrecipitationIntensity} mm</td>
            </tr>)
            }
        </tbody>
    </table>
);

fetch 可以返回被拒绝的 Promise,并且处理响应时可能会出现错误,因此您应该将获取逻辑包含在 try/catch 中。

const Weather = (props) => {
    const [weatherData, setWeatherData] = useState([]);
    const [loading, setLoading] = useState(true);
    const location = useLocation();

    useEffect(() => {
        const getWeather = async () => {
            try {
                const response = await fetch(`weather`);
                const json = await response.json();
                setWeatherData(json);
            } catch(error) {
                // handle any rejected promises or thrown errors processing response
            } finally {
                setLoading(false);
            }
        }
        getWeather();
    }, [])

    return(
        loading ? null : renderForecastTable(weatherData)
    )
}

关于javascript - 在 useEffect 中调用时 Hook 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67016257/

相关文章:

javascript - 单击时关闭 Twitter Bootstrap 下拉弹出窗口

javascript - React - 调用父组件中的函数来访问状态

javascript - 如果 JavaScript 中的函数什么都不返回..为什么?

javascript - Mobx 不观察可观察数组中的类

javascript - react 类型错误: Cannot read property 'length' of undefined

javascript - 设置状态选项卡

reactjs - useEffect 缺少依赖项

javascript - 使用 JavaScript 钩子(Hook)隐藏 Chrome 错误

reactjs - 如果有人在没有登录的情况下通过 url 访问页面,我们如何创建并返回 404 页面

javascript - 如何在同一函数中异步调用后获取更新的状态