【问题标题】:Shallow routing using withRouter and custom server not working使用 withRouter 的浅路由和自定义服务器不起作用
【发布时间】:2020-07-12 08:01:42
【问题描述】:

使用 withRouter 作为自定义服务器的包装器,浅层路由似乎不起作用。

我目前是用这个方法改路线的:

this.props.router.push({
    pathname: currentPath,
    query: currentQuery,
});

router prop 来自于使用 withRouter 来包装我的类组件。

并且不知道在哪里放置浅标志。所以我切换到文档中提到的方法:

this.props.router.push('/post/[pid]?hello=123', '/post/abc?hello=123', { shallow: true })

所以我手动执行了该操作,但我开始得到 404。

http://localhost:3000/_next/static/development/pages/search/%5Btype%5D/%5Bcat%5D/%5Barea%5D.js net::ERR_ABORTED 404 (Not Found)

解码:

"http://localhost:3000/_next/static/development/pages/search/[type]/[cat]/[area].js"

我尝试使用 :type 而不是 [type] 但它也不起作用。

这是它在服务器上的配置方式:

    if ('/search/:type/:cat/:area' === route.path) {
        return app.render(req, res, route.page);
    }

文件夹结构:

/pages/search/index.js

我认为这个结构与问题有关,因为它位于 index.js 中,而不仅仅是 pages 文件夹中的普通文件。

它不应该在更改路线时重新加载页面,这是我想要完成的主要事情。 我正在实现 SSR 分页,并且我计划使用浅层路由来使页面更改发生在客户端而不是服务器上。意味着仅在首次加载时实现 SSR,无需刷新即可保持用户。

我也试过这个:

server.get('/search/:type/:cat/:area', (req, res) => {
         console.log("reached here...");   // this gets logged
        return app.render(
            req,
            res,
            '/search/[type]/[cat]/[area]',
            req.params
        );
});

但是我得到了 404,页面现在不存在了!

这也没有用:

   this.props.router.push(
        `/search/[type]/[cat]/[area]?${stringifyQs(currentQuery)}`,
        {
            pathname: currentPath,
            query: currentQuery,
        },
        { shallow: true }
    );

【问题讨论】:

  • 404 错误可能是因为文件系统中没有pages/search/[type]/[cat]/[area].js 页面。您必须在该文件中导出一个 React 组件,该组件将为该路由路径呈现页面。很抱歉,但我很难理解您究竟想通过浅层路由实现什么。
  • this.props.router.push('/post/[pid]?hello=123', '/post/abc?hello=123', { shallow: true }) 的浅层路由仅在您已经在路径 /post/abc 上并且您尝试使用查询 hello=123 更新 URL 路径时才有效。
  • @subashMahapatra 我会给你更多细节。我使用SSR,搜索页面存在于/pages/search/index.js 中,所以你说的文件不会在那里。
  • 我们还能尝试解决这个问题吗?参数不会改变,只是查询。
  • 等一下,你的意思是更新这样的 URL。 /search?type=some-type&cat=asdfsd&area=some-area ?

标签: reactjs next.js server-side-rendering


【解决方案1】:

这应该可行:

server.js

server.get('/search/:type/:cat/:area', (req, res) => {
  return app.render(req, res, '/search', {
    ...req.params,
    ...req.query,
  });
});

pages/search/index.js

props.router.push(
  '/search?type=foo&cat=bar&area=baz&counter=10',
  '/search/foo/bar/baz?counter=10',
  { shallow: true }
);

来自GitHub的链接问题

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 2015-03-01
    • 2013-11-04
    • 2018-06-11
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多