next.js 客户端获取路由参数

22 min read

简而言之,router.query仅适用于SSR应用程序,但router.asPath仍然有效。因此,可以使用exportPathMap(非动态)在next.config.js中配置查询预导出:

return {
    '/': { page: '/' },
    '/about': { page: '/about', query: { title: 'about-us' } }
  }
}

或使用router.asPath并使用诸如query-string之类的库自己解析查询

import { withRouter } from "next/router";
import queryString from "query-string";

export const withPageRouter = Component => {
  return withRouter(({ router, ...props }) => {
    router.query = queryString.parse(router.asPath.split(/\?/)[1]);

    return <Component {...props} router={router} />;
  });
};

完整的例子

import { withRouter } from 'next/router';

/**
 * Our router to override the missing query when deploying to static export
 * This is required for page components that need access to the router
 *
 * @param {React.Component} Component
 *
 * @return {React.Component}
 */
export const withPageRouter = (Component) => {
    return withRouter(({ router, ...props }) => {
        // split at first `?`
        const searchParams = new URLSearchParams(router.asPath.split(/\?/)[1]);

        const query = {};
        for (const [key, value] of searchParams) {
            query[key] = value;
        }

        // replace the empty query
        router.query = query;

        return (<Component {...props} router={router} />);
    });
};

更推荐使用useRouter