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

React中首次调用setState后状态为空,后续更新才生效的问题

React useState状态更新后无法立即获取新值及页面不渲染的问题解决

核心问题分析

  1. setState异步特性导致console.log看不到新值
    React中useState的状态更新器(setTrendingFood)是异步批量执行的。在你调用setTrendingFood(resp)后立刻console.log(trendingFood),此时状态还没完成更新,所以打印的始终是初始的空数组[],而console.log(resp)能正确打印接口返回数据是因为它直接取的是刚拿到的响应值。

  2. 页面未渲染状态数据
    你的组件返回值里只有<div>Home</div>,完全没有用到trendingFood状态变量,所以就算状态更新成功,页面也不会有任何变化。

另外注意函数名拼写错误:fectedData应该改为fetchedData,这是个小细节但建议修正。

修改后的代码示例

import { useEffect, useState } from 'react';

const Home = () => {
  
  const [trendingFood, setTrendingFood] = useState([]);
  
  useEffect(() => {
    fetchedData();
  }, [])

  const fetchedData = async() => {
    try {
      const foodData = await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_TEMP_KEY}&number=10`);
      const resp = await foodData.json();
      // 注意:spoonacular的random接口返回结构为{ recipes: [...] },需取recipes数组
      setTrendingFood(resp.recipes);
    } catch (err) {
      console.error('数据请求失败:', err);
    }
  }

  // 渲染trendingFood数据
  return (
    <div>
      <h1>Home</h1>
      <div className="trending-foods">
        {trendingFood.length > 0 ? (
          trendingFood.map(recipe => (
            <div key={recipe.id} className="recipe-card">
              <h3>{recipe.title}</h3>
              <img src={recipe.image} alt={recipe.title} />
            </div>
          ))
        ) : (
          <p>加载中...</p>
        )}
      </div>
    </div>
  );
};

export default Home;

验证状态更新的正确方式

如果想确认状态是否更新成功,可以添加一个监听trendingFood的useEffect:

useEffect(() => {
  console.log('更新后的trendingFood:', trendingFood);
}, [trendingFood]);

这样每次trendingFood状态变化时,都会打印最新的值。

内容的提问来源于stack exchange,提问作者balu ji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:45:38