首页 > 解决方案 > 链接到动态页面时出现下一个js错误

问题描述

我有以下结构:

- blog (directory)
-- index.js (list of all blog articles)
-- [slug].js (single article)

当我在里面时,index.js我有:

const Blog = props => {
  const { pageProps: { articles } } = props
  const blogArticles = objectToArray(articles)

  return (
    <Layout bio={props.bio}>
      <Title>
        I am excited by the idea of sharing my knowledge and perhaps inspiring others.
      </Title>
      {blogArticles.map(
        (article, i) => <Card key={`id-${i}`} data={article} />
      )}
    </Layout>
  )
}

Blog.getInitialProps = async () => {
  const articles = await getBlogArticles()
  return { articles }
}

并且卡片组件具有链接:

...
    <Link href={`/blog/${slug}`}>
      <Wrapper>
        <ImgWrapper>
          <Img src={BASE_URL + url} />
        </ImgWrapper>
        <TextWrapper>
          <Title>{title}</Title>
          <ArtcilePreview>{intro}</ArtcilePreview>
        </TextWrapper>
      </Wrapper>
    </Link>
...

在里面[slug].js我有:

const BlogArticle = (props) => {
  return (
    <Layout bio={props.bio}>
      <Article title={props.pageProps.article[0].title} content={props.pageProps.article[0].content} />
      <ArticleShare url={'process.env.API_URL + asPath'} />
    </Layout>
  )
}

BlogArticle.getInitialProps = async ({ query }) => {
  const article = await getArticleBySlug(query.slug)
  return { article }
}

当我在卡片组件中单击以转到动态生成的页面时,它可以正常工作。但是,在从url/blog到的转换过程中,url/blog/my-slug我可以在控制台中看到一条错误消息迅速出现和消失。看起来它找不到动态生成的页面,抛出我认为是500 error.

我无法弄清楚为什么它出现和消失的如此之快。

下面的错误我已经录制了一个屏幕视频

在此处输入图像描述

标签: javascriptreactjsnext.js

解决方案


根据nextjs 文档,您不应该在其中添加实际的 slughref 如果您检查我在上面链接的链接的文档,正确的用法是

<Link href="/blog/[slug]" as={`/blog/${slug}`}>

推荐阅读