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

React子组件按钮无法更新父组件状态返回主页问题排查

问题解决:RecipePage返回按钮无响应

核心问题

RecipePage组件接收props的方式错误,React组件的props是以单个对象的形式传入的,你当前写成了两个独立参数(item, clickFn),导致clickFn实际为undefined,点击返回按钮时无法调用setUserRecipe修改状态。

修正步骤

  1. 调整RecipePage的props接收逻辑,通过对象解构获取recipe和clickFn
  2. 把组件内所有item.recipe的引用改为直接使用recipe

修正后的RecipePage.jsx代码

import { Box, Heading, Button as CButton, Image } from "@chakra-ui/react";

export const RecipePage = ({ recipe, clickFn }) => {
  const handleClick = () => {
    clickFn(null);
  };

  return (
    <Box ml={2}>
      <Heading>{recipe.label}</Heading>
      <Image mt={2} mb={2} h={"50%"} w={"50%"} src={recipe.image} />
      <p>
        <strong>Meal type:</strong> {recipe.mealType}
      </p>
      <p>
        <strong>Dish type:</strong> {recipe.dishType}
      </p>
      <p>
        <strong>Total cooking time:</strong> {recipe.totalTime}
      </p>
      <p>
        <strong>Diet label:</strong> {recipe.dietLabels.join(", ")}
      </p>
      <p>
        <strong>Health label:</strong> {recipe.healthLabels.join(", ")}
      </p>
      <p>
        <strong>Cautions:</strong> {recipe.cautions.join(" || ")}
      </p>
      <p>
        <strong>Ingredients:</strong> {recipe.ingredientLines.join(" || ")}
      </p>
      <p>
        <strong>Servings:</strong> {recipe.yield}
      </p>

      <CButton mt={5} type="button" onClick={handleClick}>
        Back
      </CButton>
    </Box>
  );
};

额外优化建议

  • App.jsx中useState的初始值可显式设为null,逻辑更清晰:const [userRecipe, setUserRecipe] = useState(null);
  • RecipeListPage中的key建议使用数据中的唯一ID(如果存在),避免使用label作为key(可能出现重复)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:07:16