【问题标题】:NextJS error while trying to navigate to dynamic route尝试导航到动态路由时出现 NextJS 错误
【发布时间】:2020-12-16 11:48:18
【问题描述】:

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

Error: The provided path X0UQbRIAAA_NdlgNdoes 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,
  };
};

【问题讨论】:

    标签: javascript reactjs routes next.js


    【解决方案1】:

    当您点击链接时,您的网址栏中会显示什么?如果您直接进入页面 discounts/X0UQbRIAAA_NdlgN 或通过在 url 栏中输入您的项目 id 会发生什么?

    现在我认为您的问题是您没有在括号内的链接组件中注册 slug。阅读官方文档Here的底部段落。

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

    因此,在您的&lt;Link/&gt; 组件中,href 应该使用您想要在括号中使用的名称注册 slug,然后您想要在 url 中显示的名称将在 as 属性中设置。所以它应该如下所示:

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

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

    【讨论】:

    • 它不起作用。好像我错过了什么......但我不知道是什么。很久没有用 nextjs 做东西了
    • 我已经尝试在 pages 文件夹中创建一个测试文件,它可以工作,所以我错过了 itemId 文件
    • 您的折扣文件夹在哪里?它在页面文件夹中吗?
    猜你喜欢
    • 2020-12-19
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多