Next Js自定义路线和SSR

Yas*_*obi 14 javascript node.js express react-apollo next.js

我在next上使用apollo,最近我注意到自定义路由破坏了SSR。通常,如果您浏览页面,则阿波罗会缓存查询,而当您下次访问页面时,它将处理缓存中的所有内容。但是,对于自定义路由,永远不会使用缓存。

我还注意到,当我单击这些页面时,控制台中会闪烁一个错误。但是它很快消失了,我无法在这里复制它。

Server.js

// 
   server.get('/about-us', (req, res) => app.render(req, res, '/about'));


   server.get('/about', (req, res) => res.redirect(301, '/about-us'));
Run Code Online (Sandbox Code Playgroud)

菜单点击处理程序

const navigate = link => () => {
        Router.push(link);
    };
Run Code Online (Sandbox Code Playgroud)

菜单项

export const menu = [
    {
        name: 'Home',
        url: '/',
    },
    {
        name: 'Catalogs',
        url: '/catalogs',
    },
    {
        name: 'Shop',
        url: '/shop',
    },
    {
        name: 'Wholesale',
        url: '/wholesale',
    },
    {
        name: 'About Us',
        url: '/about-us',
        prefetch: true,
    },
    {
        name: 'Contact Us',
        url: '/contact-us',
        prefetch: true,
    },
];

Run Code Online (Sandbox Code Playgroud)

根据nextjs频谱的建议,我尝试在TopNav组件中预取自定义页面,但没有成功。

const prefetch = url => {
        if (process.browser) {
            console.log('prefetching these urls', url);
            Router.prefetch(url);
        }
    };

    useEffect(() => {
        menu.forEach(menuItem => {
            if (menuItem.prefetch) {
                prefetch(menuItem.url);
            }
        });
    }, []);
Run Code Online (Sandbox Code Playgroud)

Yas*_*obi 4

I was able to figure out the problem. This is not really well documented but you need to prefetch the component. So for my case instead of prefetching /about-us I should have prefetched /about.

That's why there is as prop in the link component. Nextjs 9 just got released which fixes this issue.

https://nextjs.org/blog/next-9#dynamic-route-segments

For nextjs 9 you can save your file as [pid].js and it will catch all paths in a specific route. i.e for /products/test-product you have to create folder products and inside that add [pid].js.

I needed to query for product based on slug so I added this and voila, I have access to the slug inside my component.

Product.getInitialProps = async ({ query }) => {
    return { slug: query.pid };
};
Run Code Online (Sandbox Code Playgroud)

These issues were pretty frustrating before next 9 but it's heavily simplified and it helped me fully remove server.js.