我在 Next.js 中获取数据时遇到问题。

huangapple go评论71阅读模式
英文:

I have problem when fetching data in Next js

问题

Sure, I can help you with the errors in your code. Please provide more details about the specific errors you are encountering, and I'll do my best to assist you in resolving them.

英文:

In a Next.js project, the provided code fetches data from an external API endpoint and passes it as props to a component called Services. The Services component uses the received data to render different parts of the page based on the current URL pathname.

The data is fetched from the following API endpoint: http://back.menumizeme.com/api/get_business_info?business_id=1.

The useEffect hook is used to fetch the data when the component mounts. The useState hook is used to store the fetched data in the data state variable.

If the data has not been fetched yet, the Loading... message is displayed. Otherwise, the Services component is rendered with the data prop.

The Services component also uses a few other props, such as item and url, that are derived from the data prop to render different parts of the page based on the current URL pathname.

The Header component, which is rendered inside the Services component, displays the business logo and name. The CategorieItem and Categories components are used to display the list of categories and category items, respectively. The MyOrder component is used to display the current order.


import React, { useEffect, useState } from "react";
import Services from "../../components/Services/Services";

const ServicesPage = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(
          "http://back.menumizeme.com/api/get_business_info?business_id=1"
        );
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.error("Error fetching data", error);
      }
    }

    fetchData();
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  return (
    <div className="container h-auto">
      <Services data={data} />
    </div>
  );
};

export default ServicesPage;

Services

import Image from "next/image";
import Header from "./Header";
import CategorieItem from "@/components/Services/Categorie-Item";
import Categories from "./Categories-List";
import { useRouter } from "next/router";
import MyOrder from "./MyOrder";

const Services = ({ data }) => {
  const serverBaseURI = "http://back.menumizeme.com";
  const router = useRouter();

  // if (!data || !data.data || !data.data[0] || !data.data[0].business) {
  //   return <div>Loading....</div>;
  // }
  const item = data.data[0];

  return (
    <section className="flex">
      <Image
        src={`${serverBaseURI}/storage/${item.business.business_logo}`}
        className="object-cover w-screen h-full"
        alt="Business Logo"
        width={1000}
        height={1000}
      />
      <div className="absolute flex flex-col w-full">
        <Header item={item} url={serverBaseURI} />
        {router.pathname === "/services" && (
          <div className="mt-3 ">
            {item.category_infos.map((category, index) => (
              <Categories key={index} category={category} item={item} />
            ))}
          </div>
        )}

        {/* {router.query && (
          <div className="mt-3">
            <CategorieItem key={router.query} item={} />
          </div>
        )}
        {router.pathname === "/myOrder/myOrder" && (
          <div className="mt-3">
            <MyOrder />
          </div>
        )} */}
      </div>
    </section>
  );
};

export default Services;

import React, { useState } from "react";
import { useRouter } from "next/router";
import { menuLink } from "./constants";
import Image from "next/image";
import { close, menu, basket } from "./assets";
import { MdLocationOn, MdPhone } from "react-icons/md";

const Header = ({ item, url }) => {
  const router = useRouter();
  const [toggle, setToggle] = useState(false);

  return (
    <div className="flex flex-row w-full justify-between">
      <div className="flex">
        <Image
          src={toggle ? close : menu}
          alt="menu"
          className="w-[32px] h-[32px] mr-1 object-contain ml-[30px] mt-12 cursor-pointer"
          onClick={() => setToggle((prev) => !prev)}
        />
        <div
          className={`${
            toggle ? "flex" : "hidden"
          } bg-[#000000f1] absolute top-20 w-[98.5vw] sidebar z-[1]`}
        >
          <ul className="list-none flex flex-col justify-end items-center flex-1">
            {menuLink.map((nav, index) => (
              <li
                key={nav.id}
                className={`font-poppins font-semibold border-[#ffffff83] w-[98.5vw] cursor-pointer flex flex-col justify-center h-12 text-[18px] leading-7 text-white text-center hover:text-[#FAB25A] hover:font-bold hover:bg-[#fab25a2d] ${
                  index === menuLink.length - 1 ? "" : "border-b-[1px]"
                }`}
              >
                <a href={`#${nav.id}`}>{nav.title}</a>
              </li>
            ))}
          </ul>
        </div>
      </div>
      <div className="mt-10 flex flex-col">
        <Image
          src={`${url}/storage/${item.data.business_logo}`}
          className="object-contine"
          alt="Business Logo"
          width={1000}
          height={1000}
        />
        {router.pathname === "/services" && (
          <p className="font-Montserrat font-[700] text-lg text-[#FEFEFE] capitalize">
            {item.data.name} {item.data.businessType}
          </p>
        )}
        {router.pathname === "/services" && (
          <div className="flex-col mt-14 mx-2">
            <div className="flex flex-row mt-2">
              <MdLocationOn
                color="#A8A8A8"
                className="w-[20px] h-[20px] mt-1 mr-2"
              />
              <p className="font-Montserrat font-[400] text-lg text-[#A8A8A8]">
                {item.data.address}
              </p>
            </div>
            <div className="flex flex-row mt-2">
              <MdPhone
                color="#A8A8A8"
                className="w-[20px] h-[20px] mt-1 mr-2"
              />
              <p className="font-Montserrat font-[400] text-lg text-[#A8A8A8]">
                {item.data.phone_number}
              </p>
            </div>
          </div>
        )}
      </div>
      <div className="mr-[30px] mt-12">
        <Image src={basket} className="cursor-pointer" alt="Basket" />
      </div>
    </div>
  );
};

export default Header;

Categories

import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { useRouter } from "next/router";

const Categories = ({ category }) => {
  const router = useRouter();

  const [selectedCategory, setSelectedCategory] = useState(null);

  const handleCategoryClick = (category_id) => {
    setSelectedCategory(category_id);
    console.log(category_id);
  };

  return (
    <div className="flex flex-col">
      <Link href={`/services/${category.id}`} key={category.id}>
        <div className="flex mt-2 justify-center items-center cursor-pointer transition duration-300 ease-in-out hover:scale-110">
          {/* <Image
            src={item.logo}
            className="object-fill w-full h-[7.5rem]"
            alt={category.name}
          /> */}
          <div className="absolute w-full h-[7.5rem] flex flex-col justify-center items-center bg-[#00000054] ">
            <p className="font-Montserrat font-[700] text-[30px] leading-9 text-[#FEFEFE] capitalize ">
              {category.name}
            </p>
            <p className="font-Montserrat font-[400] text-[12px] text-[#FEFEFE] leading-3 capitalize mt-1">
              {category.description}
            </p>
          </div>
        </div>
      </Link>
    </div>
  );
};

export default Categories;

CategorieItem

import { resturant } from "@/constant/resturant";
import Image from "next/image";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import ModalOrder from "./Modal/ModalOrder";

const CategorieItem = ({ resturant }) => {
  const { query } = useRouter();
  const item = resturant;
  const [productsToShow, setProductsToShow] = useState([]);
  const [showModal, setShowModal] = useState(false);
  
  useEffect(() => {
    query?.params &&
      setProductsToShow(
        item.categories.find(
          (category) => parseInt(category.id) === parseInt(query?.params[0])
        )?.products || []
      );
  }, [query]);

  return (
    <section>
      <div className="flex flex-col">
        {productsToShow?.map((product, index) => (
          <div>
            <div
              key={index}
              className="flex flex-row w-[22rem] h-[11rem] justify-between item-center cursor-pointer mt-4 mx-auto "
              onClick={() => setShowModal(true)}
            >
              <div>
                <Image
                  src={product.image}
                  className="w-[11rem] h-[11rem] absolute cursor-pointer transition duration-300 ease-in-out hover:scale-110 rounded-full"
                />
              </div>
              <div className="flex flex-col justify-center pl-9 items-start w-[13rem] h-[8rem] bg-gradient-to-l from-[#ffffffb7] rounded-r-[13rem] my-auto ">
                <h2 className="font-Montserrat text-[#fff]  font-bold text-lg leading-5">
                  {product.name}
                </h2>
                <p className="font-Montserrat text-[#fff] font-[500] text-[12px] leading-4 my-2">
                  {product.description}
                </p>
                <p className="font-Montserrat text-[#fff] font-bold text-lg leading-5">
                  {product.price}
                </p>
              </div>
            </div>

            <div>
              <ModalOrder product={product} showModal={showModal} setShowModal={setShowModal}/>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

export default CategorieItem;

> can any one help me I got a lot of error

答案1

得分: 0

I've translated the code for you. Here are the translated parts:

Services

import Image from "next/image";
import Header from "./Header";
import CategorieItem from "@/components/Services/Categorie-Item";
import Categories from "./Categories-List";
import { useRouter } from "next/router";
import MyOrder from "./MyOrder";
import { useEffect, useState } from "react";
import Loader from "../UI/Loader";

const Services = () => {
  const serverBaseURI = "http://back.menumizeme.com";
  const router = useRouter();

  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch(
          "http://back.menumizeme.com/api/get_business_info?business_id=1"
        );
        const data = await response.json();
        setData(data);
      } catch (error) {
        console.error("Error fetching data", error);
      }
    }

    fetchData();
  }, []);

  if (!data) {
    return (
      <div className="centered-loder  w-screen  bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-[#ffd900dc] via-[#8feb17b9] to-[#ffd900dc]">
        <Loader />{" "}
      </div>
    );
  }

  const item = data.data;

  return (
    <section className="flex w-screen">
      <div className="relative h-screen w-screen">
        <Image
          src={`${serverBaseURI}/storage/${item.business_banner}`}
          className="object-cover !w-screen"
          alt="Business Logo"
          priority={false}
          fill
        />
      </div>

      <div className="absolute flex flex-col w-full">
        <Header item={item} url={serverBaseURI} />
        {router.pathname === "/services" && (
          <div className="mt-3 ">
            {item.categories.map((category) => (
              <Categories key={category.id} category={category} item={item} />
            ))}
          </div>
        )}

        {router.query && (
          <div className="mt-3">
            <CategorieItem key={router.query} item={item} />
          </div>
        )}
      </div>
    </section>
  );
};

export default Services;

Categories

import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useState } from "react";

const Categories = ({ category }) => {
  const serverBaseURI = "http://back.menumizeme.com";

  const categore = category.category_infos[0];

  return (
    <div className="flex flex-col">
      <Link href={`/services/${category.id}`} key={category.id}>
        <div className="flex mt-2 justify-center items-center cursor-pointer transition duration-300 ease-in-out hover:scale-110">
          <Image
            src={`${serverBaseURI}/storage/${category.logo}`}
            className="object-fill w-full h-[7.5rem]"
            alt={categore.name}
            width={175}
            height={175}
          />

          <div className="absolute w-full h-[7.5rem] flex flex-col justify-center items-center bg-[#00000054] ">
            <p className="font-Montserrat font-[700] text-[30px] leading-9 text-[#FEFEFE] capitalize ">
              {categore.name}
            </p>
            <p className="font-Montserrat font-[400] text-[12px] text-[#FEFEFE] leading-3 capitalize mt-1">
              {categore.description}
            </p>
          </div>
        </div>
      </Link>
    </div>
  );
};

export default Categories;

CategorieItem

import Image from "next/image";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import ModalOrder from "./Modal/ModalOrder";
import Link from "next/link";

const CategorieItem = ({ item }) => {
  const { query } = useRouter();
  const serverBaseURI = "http://back.menumizeme.com";
  const [productsToShow, setProductsToShow] = useState([]);
  const [selectProductInfo, setSelectProductInfo] = useState(null);
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    let category;
    if (query?.params && item && item.categories) {
      category = item.categories.filter(
        (category) => parseInt(category.id) === parseInt(query?.params[0])
      );
    }
    setProductsToShow(category ? category[0].products || [] : []);
  }, [query]);

  const selectProduct = (product_info) => {
    setSelectProductInfo(product_info);
    setShowModal(true);
  };

  return (
    <section>
      <div className="flex flex-col ">
        {query?.params && (
          <div className="flex justify-center items-center ">
            {item.categories.map((category) => (
              <Link href={`/services/${category.id}`} key={category.id}>
                <div className="cursor-pointer  border-2 border-[#fff] text-white hover:text-black hover:bg-[#F8B162]  rounded-full  px-4 py-1 mx-4 ">
                  <div className="font-Montserrat   text-lg font-bold tracking-wider">
                    {category.category_infos[0].name}
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}

        {productsToShow.map((product, index) => (
          <div key={index} className="flex flex-row w-[22rem] h-[11rem] justify-between item-center cursor-pointer mt-4 mx-auto " onClick={() => selectProduct(product.product_infos[0])}>
            <div>
              <Image src={`${serverBaseURI}/storage/${product.image}`} className="w-[11rem] h-[11rem] absolute cursor-pointer transition duration-300 ease-in-out hover:scale-110 rounded-full" alt="Product photo" width={300} height={300} />
            </div>
            <div className="flex flex-col justify-center pl-9 items-start w-[13rem] h-[8rem] bg-gradient-to-l from-[#ffffffb7] rounded-r-[13rem] my-auto ">
              {product.product_infos.length > 0 ? (
                product.product_infos.map((product_info) => (
                  <>
                    <h2 className="font-Montserrat text-[#fff] font-bold text-lg leading-5">
                      {product_info.name}
                    </h2>
                    <p className="font-Montserrat text-[#fff] font-[500] text-[12px] leading-4 my-2">
                      {product_info.description}
                    </p>
                  </>
                ))
              ) : (
                <p>No product information available.</p>
              )}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
};

export default CategorieItem;

Please note that some HTML tags and special characters like &quot; have been converted to their respective HTML entities for proper rendering in this text format.

英文:

I solve my problem :
the error Ihave object contine array so I do the when Passage of data

so after update :

Services

import Image from &quot;next/image&quot;;
import Header from &quot;./Header&quot;;
import CategorieItem from &quot;@/components/Services/Categorie-Item&quot;;
import Categories from &quot;./Categories-List&quot;;
import { useRouter } from &quot;next/router&quot;;
import MyOrder from &quot;./MyOrder&quot;;
import { useEffect, useState } from &quot;react&quot;;
import Loader from &quot;../UI/Loader&quot;;
const Services = () =&gt; {
const serverBaseURI = &quot;http://back.menumizeme.com&quot;;
const router = useRouter();
const [data, setData] = useState(null);
useEffect(() =&gt; {
async function fetchData() {
try {
const response = await fetch(
&quot;http://back.menumizeme.com/api/get_business_info?business_id=1&quot;
);
const data = await response.json();
setData(data);
} catch (error) {
console.error(&quot;Error fetching data&quot;, error);
}
}
fetchData();
}, []);
if (!data) {
return (
&lt;div className=&quot;centered-loder  w-screen  bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-[#ffd900dc] via-[#8feb17b9] to-[#ffd900dc]&quot;&gt;
&lt;Loader /&gt;{&quot; &quot;}
&lt;/div&gt;
);
}
const item = data.data;
return (
&lt;section className=&quot;flex w-screen&quot;&gt;
&lt;div className=&quot;relative h-screen w-screen&quot;&gt;
&lt;Image
src={`${serverBaseURI}/storage/${item.business_banner}`}
className=&quot;object-cover !w-screen&quot;
alt=&quot;Business Logo&quot;
priority={false} // {false} | {true}
fill
/&gt;
&lt;/div&gt;
&lt;div className=&quot;absolute flex flex-col w-full&quot;&gt;
&lt;Header item={item} url={serverBaseURI} /&gt;
{router.pathname === &quot;/services&quot; &amp;&amp; (
&lt;div className=&quot;mt-3 &quot;&gt;
{item.categories.map((category) =&gt; (
&lt;Categories key={category.id} category={category} item={item} /&gt;
))}
&lt;/div&gt;
)}
{router.query &amp;&amp; (
&lt;div className=&quot;mt-3&quot;&gt;
&lt;CategorieItem key={router.query} item={item} /&gt;
&lt;/div&gt;
)}
{/* {router.pathname === &quot;/myOrder/myOrder&quot; &amp;&amp; (
&lt;div className=&quot;mt-3&quot;&gt;
&lt;MyOrder /&gt;
&lt;/div&gt;
)}  */}
&lt;/div&gt;
&lt;/section&gt;
);
};
export default Services;

Categories

import Image from &quot;next/image&quot;;
import Link from &quot;next/link&quot;;
import React, { useEffect, useState } from &quot;react&quot;;
const Categories = ({ category }) =&gt; {
const serverBaseURI = &quot;http://back.menumizeme.com&quot;;
const categore = category.category_infos[0];
return (
&lt;div className=&quot;flex flex-col&quot;&gt;
&lt;Link href={`/services/${category.id}`} key={category.id}&gt;
&lt;div className=&quot;flex mt-2 justify-center items-center cursor-pointer transition duration-300 ease-in-out hover:scale-110&quot;&gt;
&lt;Image
src={`${serverBaseURI}/storage/${category.logo}`}
className=&quot;object-fill w-full h-[7.5rem]&quot;
alt={categore.name}
width={175}
height={175}
/&gt;
&lt;div className=&quot;absolute w-full h-[7.5rem] flex flex-col justify-center items-center bg-[#00000054] &quot;&gt;
&lt;p className=&quot;font-Montserrat font-[700] text-[30px] leading-9 text-[#FEFEFE] capitalize &quot;&gt;
{categore.name}
&lt;/p&gt;
&lt;p className=&quot;font-Montserrat font-[400] text-[12px] text-[#FEFEFE] leading-3 capitalize mt-1&quot;&gt;
{categore.description}
&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/Link&gt;
&lt;/div&gt;
);
};
export default Categories;

CategorieItem

import Image from &quot;next/image&quot;;
import { useRouter } from &quot;next/router&quot;;
import React, { useEffect, useState } from &quot;react&quot;;
import ModalOrder from &quot;./Modal/ModalOrder&quot;;
import Link from &quot;next/link&quot;;
const CategorieItem = ({ item }) =&gt; {
const { query } = useRouter();
const serverBaseURI = &quot;http://back.menumizeme.com&quot;;
const [productsToShow, setProductsToShow] = useState([]);
const [selectProductInfo, setSelectProductInfo] = useState(null);
const [showModal, setShowModal] = useState(false);
useEffect(() =&gt; {
let category;
if (query?.params &amp;&amp; item &amp;&amp; item.categories) {
category = item.categories.filter(
(category) =&gt; parseInt(category.id) === parseInt(query?.params[0])
);
}
setProductsToShow(category ? category[0].products || [] : []);
}, [query]);
const selectProduct = (product_info) =&gt; {
setSelectProductInfo(product_info);
setShowModal(true);
};
return (
&lt;section&gt;
&lt;div className=&quot;flex flex-col &quot;&gt;
{query?.params &amp;&amp; (
&lt;div className=&quot;flex justify-center items-center &quot;&gt;
{item.categories.map((category) =&gt; (
&lt;Link href={`/services/${category.id}`} key={category.id}&gt;
&lt;div className=&quot;cursor-pointer  border-2 border-[#fff] text-white hover:text-black hover:bg-[#F8B162]  rounded-full  px-4 py-1 mx-4 &quot;&gt;
&lt;div className=&quot;font-Montserrat   text-lg font-bold tracking-wider&quot;&gt;
{category.category_infos[0].name}
&lt;/div&gt;
&lt;/div&gt;
&lt;/Link&gt;
))}
&lt;/div&gt;
)}
{productsToShow.map(
(product, index) =&gt; (
(
&lt;div&gt;
&lt;div
key={index}
className=&quot;flex flex-row w-[22rem] h-[11rem] justify-between item-center cursor-pointer mt-4 mx-auto &quot;
onClick={() =&gt; selectProduct(product.product_infos[0])}
&gt;
&lt;div&gt;
&lt;Image
src={`${serverBaseURI}/storage/${product.image}`}
className=&quot;w-[11rem] h-[11rem] absolute cursor-pointer transition duration-300 ease-in-out hover:scale-110 rounded-full&quot;
alt=&quot;Product photo&quot;
width={300}
height={300}
/&gt;
&lt;/div&gt;
&lt;div className=&quot;flex flex-col justify-center pl-9 items-start w-[13rem] h-[8rem] bg-gradient-to-l from-[#ffffffb7] rounded-r-[13rem] my-auto &quot;&gt;
{product.product_infos.length &gt; 0 ? (
product.product_infos.map((product_info) =&gt; (
&lt;&gt;
&lt;h2 className=&quot;font-Montserrat text-[#fff] font-bold text-lg leading-5&quot;&gt;
{product_info.name}
&lt;/h2&gt;
&lt;p className=&quot;font-Montserrat text-[#fff] font-[500] text-[12px] leading-4 my-2&quot;&gt;
{product_info.description}
&lt;/p&gt;
&lt;/&gt;
))
) : (
&lt;p&gt;No product information available.&lt;/p&gt;
)}
&lt;/div&gt;
&lt;/div&gt;
{selectProductInfo &amp;&amp; (
&lt;div&gt;
&lt;ModalOrder
product={product}
productInfo={selectProductInfo}
showModal={showModal}
setShowModal={setShowModal}
/&gt;
&lt;/div&gt;
)}
&lt;/div&gt;
)
)
)}
&lt;/div&gt;
&lt;/section&gt;
);
};
export default CategorieItem;

huangapple
  • 本文由 发表于 2023年5月7日 19:18:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定