【问题标题】:NextJS: How do I get exportPathMap page data? I don't see it in getStaticPropsNextJS:如何获取 exportPathMap 页面数据?我在 getStaticProps 中看不到它
【发布时间】:2020-04-26 05:19:51
【问题描述】:

我已经设置了exportPathMap,但是从我的组件导出getStaticProps 时得到一个空对象。我不明白我应该如何访问它?

// next.config.js
exportPathMap: async function (
    defaultMapPath,
    { dev, dir, outDir, distDir, buildId }
  ) {
    const paths = {}
    const response = await fetch(...)
    const data = await response.json()
    data.forEach((item) => {
      paths[`/item/${item.id}`] = {
        page: '/itemPage',
        query: {
          item,
        },
      }
    })

    return paths
  },

// itemPage.js
...
export async function getStaticProps(props) {
  console.log('props', props) // returns "props {}""

  return {
    props: props
  }
}
...

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    目前很难在文档中找到具体说明,但这里有您的选择。

    选项 1

    像这样使用getStaticPathsgetStaticProps(来自nextJS示例中的“with-static-export”)

    // [id].js post file
    
    export async function getStaticPaths() {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/posts?_page=1'
      )
      const postList = await response.json()
      return {
        paths: postList.map(post => {
          return {
            params: {
              id: `${post.id}`,
            },
          }
        }),
        fallback: false,
      }
    }
    
    export async function getStaticProps({ params }) {
      // fetch single post detail
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/posts/${params.id}`
      )
      const post = await response.json()
      return {
        props: post,
      }
    }
    

    选项 2

    使用exportPathMapgetInitialProps

    // item.js
    ...
    Page.getInitialProps = function (context) {
      return context.query.item
    }
    
    // next.config.js
    module.exports = {
      // ...Same as in your question...
    }
    

    两者都允许您进行静态优化。 使用选项 1,您无需导出,next build 就足够了。对于选项 2,您需要运行 next export

    发件人:https://nextjs.org/docs/advanced-features/static-html-export

    如果您的页面没有 getInitialProps,您可能根本不需要下一次导出;借助自动静态优化,下一次构建已经足够了。

    另一个注意事项:您可以在单个项目中使用这两种方法。

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2021-05-11
      • 2022-11-29
      • 2020-09-15
      • 2021-09-25
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多