本文介绍了使用 withRouter 和自定义服务器的浅路由不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Using withRouter as a wrapper with custom server, shallow routing doesn't seem to be working.

我目前使用这种方法来改变路线:

I currently use this method to change the route:

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

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

router prop comes from using withRouter to wrap my class component.

并且不知道把浅旗放在哪里.所以我切换到文档中提到的方法:

And couldn't figure where to put the shallow flag. So I switched to the method mentioned in the docs:

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

所以我手动完成了,但我开始收到 404.

So I did that manually, but I started getting 404s.

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] 但它也不起作用.

I tried using :type instead of [type] but it also didn't work.

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

This is how it's configured on the server:

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

文件夹结构:

/pages/search/index.js

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

I think this structure has something to do with the problem, since it's in the index.js and not just a plain file in the pages folder.

在更改路线时不应重新加载页面,这是我要完成的主要任务.我正在实现 SSR 分页,并且我计划使用浅路由来使页面更改发生在客户端而不是服务器上.意思是只在第一次加载时实现 SSR,保持用户不刷新.

It should not reload the page while changing the route, that's the main thing I'm trying to accomplish.I'm implementing SSR pagination, and I'm planning to use shallow routing to make page changes happen on the client instead of the server. Meaning achieve SSR on first load only, keep user in without refreshing.

我也试过这个:

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,页面现在不存在!

But I'm getting 404s, the page is not there now!

这也不起作用:

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

推荐答案

这应该有效:

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

这篇关于使用 withRouter 和自定义服务器的浅路由不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:35