Shallow routing using withRouter and custom server not working

别等时光非礼了梦想. 提交于 2020-07-23 06:31:43

问题


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 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 })

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)

decoded:

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

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);
    }

Folder Structure:

/pages/search/index.js

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.

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.

I also tried this:

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
        );
});

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

This also didn't work:

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

回答1:


This should work:

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 }
);

Linked issue from GitHub



来源:https://stackoverflow.com/questions/62858582/shallow-routing-using-withrouter-and-custom-server-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!