NodeJS UseEffect()无法从API中获取数据

1l5u6lss  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(119)

我正在学习一个关于全栈应用的教程。我试图使用useEffect()从API中获取数据。我已经用心学习了教程,但我在这个问题上停留了一段时间,似乎找不到解决方法。我还使用了以下代码:
1)下面是从API获取数据的钩子。

import { useEffect, useState } from "react";
import axios from "axios";

const useFetch = (url) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const res = await axios.get(url);
        setData(res.data);
      } catch (error) {
        setError(error);
      }
      setLoading(false);
    };
    fetchData();
  }, [url]);

  return { data, loading, error };
};

export default useFetch;

2)下面是API

export const countByType = async (req, res, next) => {
  try {
    const hotelCount = await Hotel.countDocuments({ type: "Hotel" });
    const apartmentCount = await Hotel.countDocuments({ type: "apartment" });
    const resortCount = await Hotel.countDocuments({ type: "resort" });
    const villaCount = await Hotel.countDocuments({ type: "villa" });
    const cabinCount = await Hotel.countDocuments({ type: "cabin" });

    res.status(200).json([
      { type: "hotel", count: hotelCount },
      { type: "apartment", count: apartmentCount },
      { type: "resort", count: resortCount },
      { type: "villa", count: villaCount },
      { type: "cabin", count: cabinCount },
    ]);
  } catch (error) {
    next(createError(500, "Something went wrong"));
  }
};

3)在这里,我尝试使用这些数据将其呈现在我的页面上。

import useFetch from "../../hooks/useFetch.js";
import "../propertyList/propertyList.css";

const images = [
  "https://images.pexels.com/photos/189296/pexels-photo-189296.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
  "https://images.pexels.com/photos/189296/pexels-photo-189296.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
  "https://images.pexels.com/photos/189296/pexels-photo-189296.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
  "https://images.pexels.com/photos/189296/pexels-photo-189296.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
  "https://images.pexels.com/photos/189296/pexels-photo-189296.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
];

const propertyList = () => {
  const { data, loading, error } = useFetch(
    "//localhost:3000/api/hotels/countByType"
  );

  return (
    <div className="pList">
      {loading ? (
        "loading"
      ) : (
        <>
          {data &&
            images.map((img, i) => (
              <div className="pListItem">
                <img src="" alt="" className="pListImage" />
                <h1>{data[0].type}</h1>
                <span>{data[0].count}</span> <span>{data[0].type}</span>
              </div>
            ))}
        </>
      )}
    </div>
  );
};

export default propertyList;

这里是我得到的错误的照片。我不认为第一个是一个错误,但我认为它可能有助于解决这个问题。

yh2wf1be

yh2wf1be1#

在使用数据的位置添加空校验

<div className="pList">
  {loading ? (
    "loading"
  ) : (
    <>
      {data && data.length > 0 &&
        images.map((img, i) => (
          <div className="pListItem">
            <img src="" alt="" className="pListImage" />
            <h1>{data[0]?.type}</h1>
            <span>{data[0]?.count}</span> <span>{data[0].type}</span>
          </div>
        ))}
    </>
  )}
</div>

相关问题