【问题标题】:Cannot read properties of undefined (reading 'name') / (reading 'location')无法读取未定义的属性(读取“名称”)/(读取“位置”)
【发布时间】:2022-02-13 02:56:17
【问题描述】:

如何使用“无法读取未定义的属性(读取“名称”)和(读取“位置”)解决此错误,我不明白。

招摇:https://test-front.framework.team/api-docs/#/%2Flocations/locations

代码沙盒:https://codesandbox.io/s/elem-1f5t5

我希望正确显示项目块,以及我从 API 获得的所有信息

import "./styles.css";
    import { useEffect, useState } from "react";

const App = () => {
  const baseURL = "https://test-front.framework.team/";
  const [items, setItems] = useState([]);
  const [authors, setAuthors] = useState([]);
  const [locations, setLocations] = useState([]);

  useEffect(() => {
    fetch("https://test-front.framework.team/paintings")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
          console.log("paintings");
        }
      );
    fetch("https://test-front.framework.team/authors")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setAuthors(result);
          console.log("authors");
        }
      );
    fetch("https://test-front.framework.team/locations")
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setLocations(result);
          console.log("locations");
        }
      );
  }, []);

  const result = items.map((elem) => {
    return {
      author: authors.find((author) => author.id === elem.authorId).name,
      created: elem.created,
      id: elem.id,
      imgUrl: elem.imgUrl,
      location: locations.find((location) => location.id === elem.locationId)
        .location,
      name: elem.name
    };
  });

  return (
    <div className="App">
      {result.map((elem) => (
        <div key={elem.id} className={"item"}>
          <img src={`${baseURL}${elem.imageUrl}`} />
          <li className={"cardInfo"}>
            <ul>{elem.name}</ul>
            <ul> {elem.author}</ul>
            <ul>{elem.created}</ul>
            <ul>{elem.location}</ul>
          </li>
        </div>
      ))}
    </div>
  );
};

export default App;

【问题讨论】:

    标签: javascript reactjs async-await fetch


    【解决方案1】:

    因为它在请求之前呈现页面并且项目是一个空数组,您可以在 useEffect 中设置结果,如下所示:

      useEffect(() => {
        fetch("https://test-front.framework.team/paintings")
          .then((res) => res.json())
          .then(
            (result) => {
              setIsLoaded(true);
              setItems(result);
              console.log("paintings");
            }
          );
        fetch("https://test-front.framework.team/authors")
          .then((res) => res.json())
          .then(
            (result) => {
              setIsLoaded(true);
              setAuthors(result);
              console.log("authors");
            }
          );
        fetch("https://test-front.framework.team/locations")
          .then((res) => res.json())
          .then(
            (result) => {
              setIsLoaded(true);
              setLocations(result);
              console.log("locations");
            }
          );
    
      const result = items.map((elem) => {
        return {
          author: authors.find((author) => author.id === elem.authorId).name,
          created: elem.created,
          id: elem.id,
          imgUrl: elem.imgUrl,
          location: locations.find((location) => location.id === elem.locationId)
            .location,
          name: elem.name
        };
      });
      }, []);
    

    或者您可以在请求完成时设置一个布尔状态,然后使用 jsx 映射您的项目:

    import "./styles.css";
        import { useEffect, useState } from "react";
    
    const App = () => {
      const baseURL = "https://test-front.framework.team/";
      const [items, setItems] = useState([]);
      const [authors, setAuthors] = useState([]);
      const [locations, setLocations] = useState([]);
      const [hasItemsArrived , SetHasItemsArrived] = usestate(false)
    
      useEffect(() => {
        fetch("https://test-front.framework.team/paintings")
          .then((res) => res.json())
          .then(
            (result) => {
              setIsLoaded(true);
              setItems(result);
              setHasItemsArrived(true);
              console.log("paintings");
            }
          );
        fetch("https://test-front.framework.team/authors")
          .then((res) => res.json())
          .then(
            (result) => {
              setIsLoaded(true);
              setAuthors(result);
              console.log("authors");
            }
          );
        fetch("https://test-front.framework.team/locations")
          .then((res) => res.json())
          .then(
            (result) => {
              setIsLoaded(true);
              setLocations(result);
              console.log("locations");
            }
          );
      }, []);
    
      
     
    
      return (
        <div className="App">
          {hasItemsArrived && items.map((elem) => (
            <div key={elem.id} className={"item"}>
              <img src={`${baseURL}${elem.imageUrl}`} />
              <li className={"cardInfo"}>
                <ul>{elem.name}</ul>
                <ul> {elem.author}</ul>
                <ul>{elem.created}</ul>
                <ul>{elem.location}</ul>
              </li>
            </div>
          ))}
        </div>
      );
    };
    
    export default App;
     
    

    【讨论】:

      【解决方案2】:

      将图像元素的值从项目数组获取到结果时存在问题。我已经更新了您的代码沙箱,并且所有必需的属性都正确显示。 请验证。

      【讨论】:

        猜你喜欢
        • 2021-12-20
        • 2021-12-06
        • 2022-01-22
        • 2021-11-13
        • 2022-01-14
        • 2022-06-22
        • 2021-12-28
        • 1970-01-01
        • 2022-07-06
        相关资源
        最近更新 更多