【问题标题】:cant match page to URI with next.js Error: The provided path `/` does not match the page: `/[slug]`无法使用 next.js 将页面与 URI 匹配错误:提供的路径 `/` 与页面不匹配:`/[slug]`
【发布时间】:2021-04-18 18:15:41
【问题描述】:

我正在尝试使用 Wordpress 作为数据源来构建动态页面。

我没有得到正确的 getStaticProps 和 getStaticPaths 并导致错误

Error: The provided path `/` does not match the page: `/[slug]`.

出于测试目的,我现在已经对页面名称进行了硬编码(理想情况下,我想让它动态化)(我已经尝试为此制作代码和框,但我似乎总是在使用 next.js 和代码框时遇到问题)。

我导航到 http://localhost:3000/art-shows 进行测试

这是我的 [slug].js 页面

import Head from 'next/head'
import Link from 'next/link'
import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
import { CMS_NAME } from '../lib/constants'
import Header from '../components/header'



export default function Index() {

console.log(router.query)
  return (
    <>
      <Layout>
        <Head>
          <title>page</title>
        </Head>
       <Header />
        <Container>
         Hello World
          
        </Container>
      </Layout>
    </>
  )
}


export async function getStaticProps({ params }) {
    
    
  const data = await getAllPagesBySlug('/art-shows')

  return {
    props: {
      page: data.page,
  
    },
  }
}

export async function getStaticPaths() {
  const allPages = await getAllPagesWithSlug()

  return {
    paths: allPages.edges.map(({ node }) => `${node.uri}`) || [],
    fallback: true,
  }
}

这是我的连接../lib/api'

const API_URL = process.env.WORDPRESS_API_URL

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' }

  if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
    headers[
      'Authorization'
    ] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
  }

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      query,
      variables,
    }),
  })

  const json = await res.json()
  if (json.errors) {
    console.error(json.errors)
    throw new Error('Failed to fetch API')
  }
  return json.data
}


  
export async function getAllPagesBySlug($id) {
  const data = await fetchAPI(`
    {
     
        page(id: $id, idType: URI) {
            content
            isFrontPage
            isPostsPage
            uri
            title(format: RAW)
            seo {
              title
              metaDesc
              metaRobotsNofollow
              metaRobotsNoindex
            }
            featuredImage {
              node {
                sourceUrl
              }
            }
          }
    }
  `)
  return data
}


export async function getAllPagesWithSlug() {
  const data = await fetchAPI(`
    {
      pages(first: 10000) {
        edges {
          node {
            uri
          }
        }
      }
    }
  `)
  return data?.pages
}

  
  

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    如果你想获取所有的 slug,那么你的文件应该命名为 [...slug].js(注意 ... 扩展运算符)然后在文件内部使用 useRouter() 钩子并提取一个数组像这样的蛞蝓:

     const router = useRouter();
     const slug   = router.query.slug || [];
    

    示例:https://codesandbox.io/s/twilight-darkness-ktpd2?file=/pages/%5B...slug%5D.js

    如果你 fork 上面的沙盒链接,那么你将有一个 nextjs 模板来使用代码代码沙盒。如果上述方法不起作用,请分叉沙箱并将您的代码放入并告诉我,以便我查看。

    【讨论】:

    • 谢谢你..在我开始之前我有几个问题如果你不介意..我正在使用 Wordpress 下一个无头模板..它使用 [slug].js 加载所有的博客文章.. 但显然我不能将 slug 用于页面(根据 GraphQL)我需要与 uri 匹配......我应该使用 [uri].js 吗?为什么 [slug].js 对博客文章有效?
    • 我没有使用 wordpress next 无头模板,只是 nextjs 就像你上面的例子一样。您能否发送一个指向您正在使用的模板的链接,以便我查看您正在使用的模板? [slug].js 用于获取该目录内的动态页面。 /blog/this-is-a-post 会将 this-is-a-post 传递给 [slug] 文件。这就是为什么它非常适合博客文章。但是,/blog/this-is-a-post/more 不会被传递,因为它更深 1 个 slug(目录级别)。
    【解决方案2】:

    再次感谢。我把所有的博客都放到了它自己的文件夹中,我把页面留在了根文件夹中。我终于让它像这样工作了。

    [slug.js] 很多变化

    import Head from 'next/head'
    import Link from 'next/link'
    import Container from '../components/container'
    import MoreStories from '../components/more-stories'
    import HeroPost from '../components/hero-post'
    import Intro from '../components/intro'
    import Layout from '../components/layout'
    import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
    import { CMS_NAME } from '../lib/constants'
    import Header from '../components/header'
    
    
    
    export default function Page( {page} ) {
    
    
      return (
        <>
          <Layout>
            <Head>
              <title></title>
            </Head>
           <Header />
            <Container>
            <div dangerouslySetInnerHTML={{ __html: page.content }} />
            
              
            </Container>
          </Layout>
        </>
      )
    }
    
    
    
    
    export async function getStaticProps({ params }) {
        
      const data = await getAllPagesBySlug(params.slug)
      console.log(data)
      
      
      return {
        props: {
          page: data.page,
      
        },
      }
    }
    
    
    
    
    export async function getStaticPaths() {
      const allPages = await getAllPagesWithSlug()
    
      return {
         
         //paths:  [ { params: { slug: '${node.uri}' } }  ],
        paths: allPages.edges.map(({ node }) => `/${node.slug}`) || [],
        fallback: true,
      }
    }
    

    和查询修改(page(id: "${$id}", idType: URI) {)

    export async function getAllPagesBySlug($id) {
      const data = await fetchAPI(`
        {
         
            page(id: "${$id}", idType: URI) {
                content
                isFrontPage
                isPostsPage
                uri
                content
                title(format: RAW)
                featuredImage {
                  node {
                    sourceUrl
                  }
                }
              }
        }
      `)
      return data
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 2019-02-02
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2020-10-03
      • 2020-05-17
      相关资源
      最近更新 更多