如何使用Context API将{id}属性传递到我的Next.js动态路由?

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

How can I pass an {id} property to my Next.js dynamic route using Context API?

问题

以下是翻译好的部分:

  1. 对于 CartItem 组件的代码块:
import Link from 'next/link';
import styles from './CartItem.module.css';
import { useState, useEffect } from 'react';
import { useAppStore } from '../../app/Context/store';

const CartItem = ({ data }) => {
    const [addedToCart, setAddedToCart] = useState(false);
    const { addToCart, cartItems } = useAppStore();

    useEffect(() => {
        if (cartItems.some(cartItem => cartItem.id === data.id)) {
            setAddedToCart(true);
        } else {
            setAddedToCart(false);
        }
    }, [cartItems]);

    const handleAddToCart = data => {
        if (cartItems.some(cartItem => cartItem.title === data.title)) {
            setAddedToCart(true);
        } else {
            addToCart(data);
            setAddedToCart(true);
            console.log(data);
            console.log(cartItems);
        }
    };

    return (
        <>
            <div className={styles.productCard}>
                <Link href={`/cartItemPage/${data.id}`}>
                    <div className='flex items-center flex-col'>
                        <img className={styles.productImage} src={data.image} alt={data.title} />
                        <h3 className={styles.productTitle}>{data.title}</h3>
                        <p className={styles.productPrice}>{data.price} $</p>

                        {/* Additional details */}
                    </div>
                </Link>
                <button
                    onClick={() => {
                        handleAddToCart(data);
                    }}
                    className={addedToCart ? styles.addedButton : styles.addButton}
                >
                    {addedToCart ? 'In Cart' : 'Add to Cart'}
                </button>
            </div>
        </>
    );
};

export default CartItem;
  1. 对于 CartItemPage 组件的代码块:
import React, { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAppStore } from '@/app/Context/store';

const CartItemPage = ({ id }) => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const { addToCart, cartItems } = useAppStore();
    const [cartItem, setCartItem] = useState(null);

    useEffect(() => {
        const fetchCartItem = async () => {
            try {
                const response = await fetch(`https://fakestoreapi.com/products/${id}`);
                const data = await response.json();
                setCartItem(data);
            } catch (error) {
                console.log(error);
            }
        };

        if (id) {
            fetchCartItem();
        }
    }, [id]);

    return (
        <>
            <div>id: {id}</div>
        </>
    );
};

export default CartItemPage;

希望这些翻译能够帮助您更好地理解代码。

英文:

I have a problem with passing the ${id} property to my dynamic route [id]&gt;page.jsx, which is inside the CartItemPage.jsx file. I'm using the Context API, similar to React, where I store an array of CartItems and render my Cart with this array. I have a home page and a catalog page, and there are ProductItem components. When I click on them, I need to navigate the user to CartItemPage[id] of that specific product, but I'm having trouble getting the id property.

Here is the code for my CartItem component (actually a product):

&#39;use client&#39;;
import Link from &#39;next/link&#39;;
import styles from &#39;./CartItem.module.css&#39;;
import { useState, useEffect } from &#39;react&#39;;
import { useAppStore } from &#39;../../app/Context/store&#39;;
const CartItem = ({ data }) =&gt; {
const [addedToCart, setAddedToCart] = useState(false);
const { addToCart, cartItems } = useAppStore();
useEffect(() =&gt; {
if (cartItems.some(cartItem =&gt; cartItem.id === data.id)) {
setAddedToCart(true);
} else {
setAddedToCart(false);
}
}, [cartItems]);
const handleAddToCart = data =&gt; {
if (cartItems.some(cartItem =&gt; cartItem.title === data.title)) {
setAddedToCart(true);
} else {
addToCart(data);
setAddedToCart(true);
console.log(data);
console.log(cartItems);
}
};
return (
&lt;&gt;
&lt;div className={styles.productCard}&gt;
&lt;Link href={`/cartItemPage/${data.id}`}&gt;
&lt;div className=&#39;flex items-center flex-col&#39;&gt;
&lt;img className={styles.productImage} src={data.image} alt={data.title} /&gt;
&lt;h3 className={styles.productTitle}&gt;{data.title}&lt;/h3&gt;
&lt;p className={styles.productPrice}&gt;{data.price} $&lt;/p&gt;
{/* Додаткові деталі */}
&lt;/div&gt;
&lt;/Link&gt;
&lt;button
onClick={() =&gt; {
handleAddToCart(data);
}}
className={addedToCart ? styles.addedButton : styles.addButton}
&gt;
{addedToCart ? &#39;У кошику&#39; : &#39;До кошику&#39;}
&lt;/button&gt;
&lt;/div&gt;
&lt;/&gt;
);
};
export default CartItem;

here is a code of CartItemPage, where i created [id] &gt; page.jsx:

&#39;use client&#39;;
import React, { useEffect, useState } from &#39;react&#39;;
import { useRouter, useSearchParams } from &#39;next/navigation&#39;;
import { useAppStore } from &#39;@/app/Context/store&#39;;
const CartItemPage = ({ id }) =&gt; {
const router = useRouter();
const searchParams = useSearchParams();
const { addToCart, cartItems } = useAppStore();
const [cartItem, setCartItem] = useState(null);
useEffect(() =&gt; {
const fetchCartItem = async () =&gt; {
try {
const response = await fetch(`https://fakestoreapi.com/products/${id}`);
const data = await response.json(response.data);
setCartItem(data);
} catch (error) {
console.log(error);
}
};
if (id) {
fetchCartItem();
}
}, [id]);
return (
&lt;&gt;
&lt;div&gt;id: {id}&lt;/div&gt;
&lt;/&gt;
);
};
export default CartItemPage;

答案1

得分: 1

以下是您要求的代码部分的翻译:

"use client";
import React, { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAppStore } from "@/app/Context/store";

const CartItemPage = ({ params }) => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { addToCart, cartItems } = useAppStore();
  const [cartItem, setCartItem] = useState(null);

  useEffect(() => {
    const fetchCartItem = async () => {
      try {
        const response = await fetch(`https://fakestoreapi.com/products/${params.id}`);
        const data = await response.json(response.data);
        setCartItem(data);
      } catch (error) {
        console.log(error);
      }
    };

    if (params.id) {
      fetchCartItem();
    }
  }, [params]);

  return (
    <>
      <div>id: {params.id}</div>
    </>
  );
};

export default CartItemPage;

请注意,我已将代码中的 id 参数更改为 params,以及在 fetch 请求中将 id 更改为 params.id

英文:

Hey there!

You simply have to rename the id parameter to params and if you want to refer to the id just use params.id.

Like here is your updated code for CartItemPage.jsx:

Edit

Also make sure that the page.js file for your CartItemPage is inside a directory called [id]. So the file structure should be cart &gt; [id] &gt; page.js.

&quot;use client&quot;;
import React, { useEffect, useState } from &quot;react&quot;;
import { useRouter, useSearchParams } from &quot;next/navigation&quot;;
import { useAppStore } from &quot;@/app/Context/store&quot;;

const CartItemPage = ({ params }) =&gt; {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { addToCart, cartItems } = useAppStore();
  const [cartItem, setCartItem] = useState(null);

  useEffect(() =&gt; {
    const fetchCartItem = async () =&gt; {
      try {
        const response = await fetch(`https://fakestoreapi.com/products/${id}`);
        const data = await response.json(response.data);
        setCartItem(data);
      } catch (error) {
        console.log(error);
      }
    };

    if (params.id) {
      fetchCartItem();
    }
  }, [params]);

  return (
    &lt;&gt;
      &lt;div&gt;id: {params.id}&lt;/div&gt;
    &lt;/&gt;
  );
};

export default CartItemPage;

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

发表评论

匿名网友

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

确定