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

ReactJS中getTour函数返回空对象问题求助

问题分析与修复

你的getTour函数存在几个关键问题,导致无法返回正确的tour对象:

  • 误用map方法:map的作用是遍历数组生成新数组,不是查找单个元素。嵌套使用两次map后,最终返回的是一个和cities长度一致的数组(内层map没找到匹配项时会返回undefined),而非你需要的单个tour对象。
  • 缺少返回值传递:内层city.tours.map(...)的返回结果没有传递给外层map,外层map也没有返回任何内容,最终数组里全是undefined。
  • 初始值与返回类型不匹配:你初始把tour设为空对象,但最终返回的是数组,调用getTour().name自然取不到值。

修复方案

方法一:扁平化数组后查找(简洁高效)

先把所有城市的tour合并成一个数组,再用find方法匹配id:

import cities from '../data.json';
import { useParams } from "react-router-dom";
import React from 'react';

export default function Tour() {
  const { id } = useParams();
  const idAsNumber = Number(id);

  // 用useMemo缓存结果,避免每次渲染重复计算
  const tour = React.useMemo(() => {
    // 扁平化所有tour数组
    const allTours = cities.flatMap(city => city.tours);
    // 查找匹配id的tour,没找到返回空对象避免报错
    return allTours.find(tour => tour.id === idAsNumber) || {};
  }, [idAsNumber]);

  const [value, setValue] = React.useState(0);
  
  return (
    <Container sx={{ width: 900 }}>
      <Typography variant="h3" component="h1" marginTop={3}>
        {tour.name}
      </Typography>
      <Box marginTop={3} sx={{ display: "flex" }}>
        <img
          src={tour.image}
          height={325}
          alt={tour.name}
        />
        {/* 补充剩余渲染内容 */}
      </Box>
    </Container>
  );
}

方法二:嵌套查找(适合不想扁平化数组的场景)

通过循环遍历城市,在每个城市的tour列表里查找匹配项:

const tour = React.useMemo(() => {
  for (const city of cities) {
    const foundTour = city.tours.find(tour => tour.id === idAsNumber);
    if (foundTour) {
      return foundTour;
    }
  }
  return {};
}, [idAsNumber]);

额外优化点

  • 用useMemo缓存查找结果,避免组件每次渲染时重复遍历数组,提升性能。
  • 给img标签添加alt属性,符合无障碍访问规范。
  • 确保data.json里的tour对象确实包含id(数字类型)、name、image这些字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:32:22