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

React useEffect更新State:如何将数据存入all_categories

解决React State嵌套数组的更新问题

我懂你现在的困扰——明明想把获取到的分类数据塞进all_categories数组里,结果却跑到和all_categories、current_category同级的位置去了。问题出在你更新state的逻辑上:直接展开categories_data['drinks']会把数组里的每个对象都变成state的顶级属性,完全没按你想要的路径走。

正确的更新姿势

要修改嵌套在state里的数组,得逐层保留原有state的结构,只针对性修改目标数组。具体到你的代码里,在setCategory的回调里这么做:

  1. 先用扩展运算符...prev_state保留住原有state的所有属性(比如current_category),避免被覆盖
  2. 对all_categories数组,把新获取的分类数据追加进去——同样用扩展运算符把新旧数组合并成新数组

修改后的完整代码如下:

const [ categories, setCategory ] = useState({ all_categories: [], current_category: 'Cocktail' });
const [recipes, setRecipe] = useState([]);

useEffect(() => {
  Promise.all( [
    fetch(`https://the-cocktail-db.p.rapidapi.com/filter.php?c=${categories['current_category']}`, {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
        "x-rapidapi-key": "xxx"
      }
    }),
    fetch("https://the-cocktail-db.p.rapidapi.com/list.php?c=list", {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
        "x-rapidapi-key": "xxx"
      }
    })
  ] )
  .then(([response1, response2]) => {
    return Promise.all([response1.json(), response2.json()])
  })
  .then(([drinks_data, categories_data]) => {
    setRecipe(drinks_data['drinks'])
    // 核心修改部分
    setCategory(prev_state => {
      return {
        ...prev_state, // 完整保留原有state的所有属性
        all_categories: [...prev_state.all_categories, ...categories_data['drinks']] // 合并旧数组与新数据
      };
    });
  })
  .catch(err => {
    console.log(err);
  });
},[]);

关键逻辑说明

  • ...prev_state:确保current_category这类不需要修改的属性不会被清空,完整继承原有状态结构
  • [...prev_state.all_categories, ...categories_data['drinks']]:把原all_categories的所有元素和新获取的分类数组元素合并成新数组,这样新数据就会乖乖进入all_categories数组里,不会乱跑了

这么改完之后,你获取到的分类对象就能准确存到目标位置啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:02:26