【问题标题】:Why do I get this error (TypeError) when I loop through an object using react?为什么我在使用 react 遍历对象时会收到此错误 (TypeError)?
【发布时间】:2022-01-14 12:21:20
【问题描述】:

TypeError: Cannot read properties of undefined (reading 'city')

我正在尝试遍历地址键和值,但失败了,然后我尝试一次访问一个值,我得到了那个错误。我是 React 和 JS 的新手。当我尝试记录该值时,我得到了没有问题的答案,但是一旦我想在屏幕上打印出来,就会弹出错误。我已经尝试了我能想到并在网上找到的可能方法,但遗憾的是没有任何效果。

//this is a component that is supposed to show details of each hero
const HeroPage = () => {
const { id } = useParams();
const [hero, setHero] = useState({});

  useEffect(() => {
    const fetchHero = async () => {
      const res = await fetch(
        `https://jsonplaceholder.typicode.com/users/${id}`);
      const data = await res.json();
      setHero(data);
    };

    fetchHero();
  }, [id]);

  const address = hero.address;

  return (
    <div className="card-container-page box">
      <div className="box-middle">
        <h1>{hero.name}</h1>
        <h3>{hero.email}</h3>
        <h3>{hero.phone}</h3>
        <h3>{address.city}</h3>
// I have also tried the following code 
        {Object.keys(hero).map((keyName, i) => (
          <li className="card-container" key={i}>
            <span className="input-label">
              key: {i} Name: {hero[keyName]}
            </span>
          </li>
        ))}

      </div>
    </div>
  );
};

export default HeroPage;


//JSON response I get

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }]

//https://jsonplaceholder.typicode.com/users

【问题讨论】:

  • 请出示相关代码。这里没有循环。
  • 无关,但你的useEffect除了id之外,还应该依赖herosetHero
  • const { id } = useParams(); const [英雄,setHero] = useState({});我使用 map() 循环遍历它并没有工作。
  • 请编辑问题以显示您尝试过的内容。
  • @Codebling 我刚刚编辑了代码以包含我之前尝试过的内容。我不明白为什么。

标签: javascript reactjs json


【解决方案1】:

看起来您的 JSON 响应是一个对象数组。

此代码会将 JSON 响应设置为 Hero 状态变量。

    const fetchHero = async () => {
      const res = await fetch(
        `https://jsonplaceholder.typicode.com/users/${id}`
      );
      const data = await res.json();

      setHero(data);

英雄的类型现在是一个数组。所以这条线将是未定义的:

  const address = hero.address;

请尝试访问数组的第一个元素,如下所示:

  const address = hero[0].address;

如果我们要把它重构为一个工作组件,你会写这样的东西。

const HeroPage = (props) => {
  const [hero, setHero] = useState();

  useEffect(() => {
    const fetchHero = async () => {
      const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
      const data = await res.json();

      setHero(data);
    };

    fetchHero();
  }, [id]);

  if (hero === undefined) {
    return null;
  }

  return (
    <div key={hero.id} className="card-container-page box">
      <div className="box-middle">
        <h1>{hero.name}</h1>
        <h3>{hero.email}</h3>
        <h3>{hero.phone}</h3>
        <h3>{hero.address.city}</h3>
      </div>
    </div>
  );
};

export default HeroPage;

编辑:在假设 hero 是一个对象的情况下重新设计示例。

注意检查 hero === 是否未定义。这是必要的,因为在初始化状态时,它的值是未定义的,在 fetchHero 获得响应并将其保存在状态变量中之前。

【讨论】:

  • 感谢您的回复。我尝试了上面的代码,我得到了这个错误:TypeError: Cannot read properties of undefined (reading 'address')
  • 这是我组件的顶部。常量 { id } = useParams(); const [英雄,setHero] = useState({});
  • 上面的代码给出了我之前尝试使用 map 运行它时遇到的错误 "TypeError: hero.map is not a function" 这个页面应该显示一个英雄的详细信息,并且它会这样做,直到我想访问像地址这样的嵌套对象。
  • @davidio 你确定 fetchHero 的响应形状吗?您为 //https://jsonplaceholder.typicode.com/users 提供了示例响应,但在 fetchHero 中您有 https://jsonplaceholder.typicode.com/users/${id}。我怀疑 fetchHero 返回一个对象,而不是一个数组?
  • @davidio 我已经更新了我的示例代码,假设 fetchHero 返回一个对象而不是数组。
猜你喜欢
  • 2023-03-16
  • 2018-06-22
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多