reactjs 无法在NextJS中为来自Medium API的路由设置动态路由

pcww981p  于 2023-02-22  发布在  React
关注(0)|答案(1)|浏览(121)

我似乎在Next应用程序中设置动态路由时遇到问题。我尝试使用unofficial Medium API显示我在www.example.com上Medium.com的帖子。我可以在主页上显示帖子的卡片列表,并且希望每个帖子都使用Medium.com的url路径链接到应用程序中相应的页面。
API返回Medium上帖子的转义完整URL。例如"url":"https:\\/\\/medium.com\\/@myprofile\\/some-post-title-81afcccca8a7",然后我将域切掉,只使用Next应用的动态路径中的路径。我在“post”目录中添加了一个[...slug].js页面,当我点击主页上明信片上的链接时,它确实试图解析为mywebsite.com/post/some-post-title-81afcccca8a7,但我得到了错误。
我不完全确定正确设置[...slug].js的最佳方法。
在我的index.js中,我使用getStaticProps从Medium API中获取帖子的详细信息,并在其中执行以下操作(Medium API需要传递包含API密钥和主机的头文件)。

const res = await fetch(url, options).catch((e) => {
    console.error('Error fetching data', e)
    return {
      props: { error: true }, // will be passed to the page component as props
    }
  })

  const data = await res.json()
  var article_ids = data.associated_articles

  var articleDataArr = []

  for (const article_id of article_ids) {
    let article = await fetch(
      `https://medium2.p.rapidapi.com/article/${article_id}`,
      options,
    )
    const articleData = await article.text()
    articleDataArr.push(articleData)

  }

  return {
    props: {
      articleDataArr,
    }

有人能解释一下如何设置[..slug].js页面吗?

o75abkj4

o75abkj41#

你需要帖子的spread语法吗?如果你像你说的那样对域进行切片,[...slug]将返回["some-post-title-81afcccca8a7"],作为一个长度为1的数组。
如果你只需要把article_id传递到你的getStaticProps中,把[...slug]改为[slug],你会得到article_id变量"some-post-title-81afcccca8a7",你的实现中的其他东西看起来都很好,只要把扩展语法从你的文件名中去掉就行了。

相关问题