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

React子组件向父组件传Props报错及数据传递问题求助

问题修复方案

一、解决Uncaught TypeError: props.setSelectedCategory is not a function错误

错误原因

在CustomerPage的getLayout静态方法中,错误尝试从page.props获取setSelectedCategory和selectedCategory,但page是CustomerPage自身实例,这两个值是组件内部state而非props,导致传递给Layout的setSelectedCategory为undefined,最终SideNav调用时触发类型错误。

修复步骤

移除CustomerPage中的静态getLayout方法,改为在组件内部直接渲染CustomerLayout并传递state值和setter:

const CustomerPage = () => {
  const [selectedCategory, setSelectedCategory] = useState(0);
  const [products, setProducts] = useState([]);
  const [reviews, setReviews] = useState([]);

  // ...其他代码(如useEffect逻辑)

  return (
    <CustomerLayout
      setSelectedCategory={setSelectedCategory}
      selectedCategory={selectedCategory}
    >
      {/* 页面原有内容 */}
    </CustomerLayout>
  );
};

export default CustomerPage;

这样Layout能正确接收setSelectedCategory函数,传递给SideNav后,点击分类时可正常触发状态更新。

二、修复useEffect无法获取更新后selectedCategory的问题

错误原因

  1. 模板字符串误用单引号('),导致${selectedCategory}无法解析为变量,生成固定字面量URL而非动态路径;
  2. console.log("reviews,", reviews)在异步fetch完成前执行,此时reviews仍是旧值;
  3. URL路径拼写错误:categeory应为category。

修复步骤

修改useEffect中的代码:

useEffect(() => {
  console.log("selectedcat", selectedCategory);
  let url;
  if (selectedCategory !== 0) {
    // 用反引号包裹模板字符串,修正拼写错误
    url = `http://localhost:8282/product/category/${selectedCategory}`;
  } else {
    url = 'http://localhost:8282/product/all';
  }
  console.log("url", url);

  fetch(url)
    .then(response => response.json())
    .then(data => {
      setProducts(data);
    });

  fetch('http://localhost:8282/product/reviews/all')
    .then(response => response.json())
    .then(data => {
      setReviews(data);
      // 异步请求完成后再打印最新reviews数据
      console.log("reviews:", data);
    });
}, [selectedCategory]);

修改后,selectedCategory更新时会生成正确的动态URL,且能在异步请求完成后获取最新的reviews数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:37:32