尝试导航到动态路线时出现NextJS错误

时间:2020-08-27 14:48:43

标签: javascript reactjs routes next.js

我正在制作下一个js应用程序,它包含动态路由。由于某种原因,我收到一条消息,提示:

Error: The provided path X0UQbRIAAA_NdlgN does not match the page: / discounts / [itemId]`。'

我不确定问题是否与ID有关。这不是我第一次这样做,所以我很想解决这个问题

动态组件称为[itemId] .tsx,它位于折扣文件夹中。

主仪表板

import React, { useState } from 'react';
import Link from 'next/link';
import { fetchApi } from '../lib/api-prismic';
import DiscountCard from '../components/DiscountCard';
import { Container, Heading, DiscountGrid } from '../styles/DiscountPageStyles';
import { motion, AnimateSharedLayout, AnimatePresence } from 'framer-motion';

export interface DiscountItem {
  node: {
    _meta: {
      id: string;
    };
    from: string;
    category: string;
    url_without_discount: string;
    discount_code: string;
    full_url: string;
    still_available: boolean;
    post_date: string;
  };
}

interface DashboardProps {
  discountItems: DiscountItem[];
}

const DiscountsDashboard: React.FC<DashboardProps> = ({ discountItems }) => {
  const [selectedCardId, setSelectedCardId] = useState<string | null>(null);

  return (
    <AnimateSharedLayout type="crossfade">
      <Container>
        <Heading>
          <h1>Discounter</h1>
        </Heading>

        <DiscountGrid>
          {discountItems.map((item) => (
            <Link
              href={`/discounts/${item.node._meta.id}`}
              key={item.node._meta.id}
            >
              <motion.div
                whileHover={{ scale: 1.1 }}
                layoutId={item.node._meta.id}
              >
                <DiscountCard itemDetails={item} />
              </motion.div>
            </Link>
          ))}
        </DiscountGrid>
      </Container>
    </AnimateSharedLayout>
  );
};

export default DiscountsDashboard;

export async function getServerSideProps() {
  const discountItems = await fetchApi(
    `
    query {
      allDiscountitems {
        edges {
           node {
            _meta {
              id
            }
            from
            post_date
            still_available
            category 
          }
        }
      }
    }
    
  `,
    {}
  );

  return {
    props: {
      discountItems: discountItems.allDiscountitems.edges,
    },
  };
}

[itemId] .tsx

import React from 'react';

import {
  Wrapper,
  Container,
  Group,
  From,
  Availability,
  Content,
  Original,
  Code,
  Full,
  StillValid,
} from '../../styles/Modal';

import { AnimatePresence } from 'framer-motion';
import { DiscountItem } from '../discounts-dashboard';
import { fetchApi } from '../../lib/api-prismic';
import { GetStaticPaths, GetStaticProps } from 'next';

const SelectedModal = () => {
  return (
    <Wrapper>
      {/* <Container>
        <Group>
          <From>{selectedItem.node.from}</From>

          <Availability>Posted: {selectedItem.node.post_date}</Availability>
        </Group>

        <Content>
          {selectedId && (
            <AnimatePresence>
              <Group>
                <Original>
                  Original URL: {selectedItem.node.url_without_discount}
                </Original>
                <Code>Discount Code: {selectedItem.node.discount_code}</Code>
              </Group>

              <Full>
                Complete URL:{' '}
                <a href={selectedItem.node.full_url}>
                  {selectedItem.node.full_url}
                </a>
              </Full>
            </AnimatePresence>
          )}

          <StillValid>
            <section
              style={{
                background: selectedItem.node.still_available
                  ? 'var(--bg-green)'
                  : 'var(--bg-red)',
              }}
            >
              <p
                style={{
                  color: selectedItem.node.still_available
                    ? 'var(--strong-green)'
                    : 'var(--strong-red)',
                }}
              >
                {selectedItem.node.still_available
                  ? 'Available'
                  : 'Unavailable'}
              </p>
            </section>

            <p>{selectedItem.node.category}</p>
          </StillValid>
        </Content>
      </Container> */}
    </Wrapper>
  );
};

export default SelectedModal;

export const getStaticPaths: GetStaticPaths = async () => {
  const ids = await fetchApi(
    `
    query {
      allDiscountitems {
        edges {
          node {
           _meta {
              id
            }
          }
        }
      }
    }
  `,
    {}
  );

  const allIds = ids.allDiscountitems.edges.map(
    (item: DiscountItem) => item.node._meta.id
  );

  return {
    paths: allIds,
    fallback: true,
  };
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const post = fetchApi(
    `
    query {
      allDiscountitems(id: $identifier) {
        edges {
          node {
            _meta {
              id
            }
            from
            post_date
            still_available
            category 
          }
        }
      }
    }
  `,
    { identifier: params.id }
  );

  console.log(post);

  return {
    props: post,
  };
};

1 个答案:

答案 0 :(得分:0)

单击链接时,URL栏中显示什么?如果您直接进入页面discounts/X0UQbRIAAA_NdlgN或通过在网址栏中输入商品ID,会发生什么情况?

现在,我认为您的问题是您没有在子弹中的链接组件中注册该子弹。阅读官方文档Here的底部。

使用链接或路由器路由到动态路由时,您需要将href指定为动态路由,例如/ post / [pid],并指定为URL的装饰器,例如/ post / abc。

因此,在您的<Link/>组件中,href应将您要使用的名称注册到方括号中,例如,然后您要显示在url中的名称将在as属性中设置。因此,它应该类似于以下内容:

<Link
  href='/discounts/[itemId]'
  as={`/discounts/${item.node._meta.id}`}
  key={item.node._meta.id}
>
  // your link content
</Link>

然后,您可以在导航到页面时在组件中捕获[itemId]