Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用于静态导出的Next.js动态页面参数_Javascript_Reactjs_Next.js - Fatal编程技术网

Javascript 用于静态导出的Next.js动态页面参数

Javascript 用于静态导出的Next.js动态页面参数,javascript,reactjs,next.js,Javascript,Reactjs,Next.js,我有一个页面,它取决于路由参数(例如:slug),比如sohttp://example.com/blog/:slug。在我的next.config.js文件中正确定义了此路由路径: module.exports = withPlugins(plugins, { exportPathMap: (defaultPathMap) => { return { '/': { page: '/home/home' }, '/blog/:slug': { page:

我有一个页面,它取决于路由参数(例如:slug),比如so
http://example.com/blog/:slug
。在我的next.config.js文件中正确定义了此路由路径:

module.exports = withPlugins(plugins, {
  exportPathMap: (defaultPathMap) => {
    return {
      '/': { page: '/home/home' },
      '/blog/:slug': { page: '/careers/careers' }
    }
  }
});
在dev模式下运行项目时,这很好,但是一旦我将项目导出为静态,路由就不可访问,并且我从next获得了常规的404错误

有没有一种不使用查询参数的方法来解决这个问题?
http://example.com/?slug=123


此解决方案也不可接受,因为帖子来自后端CMS,这是不可能的,因为Next.js静态导出生成静态html页面。如果您仔细想想,为了让它工作,Next.js必须以某种方式导出url段中所有可能的有效字母组合,这根本不是一个好主意

最接近的方法是使用查询参数和
as
属性,例如链接到页面时:

<Link href='/blog/page?slug=SLUG_HERE' as='/blog/slug'>
  // Link content here
</Link>

//在此处链接内容

这仅在用户尝试链接或重新加载页面时中断,因为服务器端不支持屏蔽。理论上,您可以使用Nginx或Apache来代理(proxy是正确的词吗?)从这里的
/blog/SLUG\u
到这里的
/blog/page?SLUG=SLUG\u的请求。这由您自己决定。

在下一个js项目中处理动态路径(前提是您要通过导出路径!)

  • 确保trailingSlash设置为false或在next.config.js文件中未定义
这样,每个请求都会到达索引组件,从这里开始,您可以处理路径重定向

if (window.location.pathname !== "/") {
   Router.push(window.location.pathname + window.location.search);
}

确保在执行此操作之前安装了项目(例如,使用useEffect挂钩执行此操作)

请参阅类似问题和解决方案: