How can I get (query string) parameters from the URL in Next.js?

后端 未结 8 522
情深已故
情深已故 2020-12-13 01:32

When I click on a link in my /index.js, it brings me to /about.js page.

However, when I\'m passing parameter name through URL (like

相关标签:
8条回答
  • 2020-12-13 02:13

    Post.getInitialProps = async function(context) {
    
      const data = {}
      try{
        data.queryParam = queryString.parse(context.req.url.split('?')[1]);
      }catch(err){
        data.queryParam = queryString.parse(window.location.search);
      }
      return { data };
    };

    0 讨论(0)
  • 2020-12-13 02:16

    url prop is deprecated as of Next.js version 6: https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md

    To get the query parameters, use getInitialProps:

    For stateless components

    import Link from 'next/link'
    const About = ({query}) => (
      <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
    )
    
    About.getInitialProps = ({query}) => {
      return {query}
    }
    
    export default About;
    

    For regular components

    class About extends React.Component {
    
      static getInitialProps({query}) {
        return {query}
      }
    
      render() {
        console.log(this.props.query) // The query is available in the props object
        return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
    
      }
    }
    

    The query object will be like: url.com?a=1&b=2&c=3 becomes: {a:1, b:2, c:3}

    0 讨论(0)
  • 2020-12-13 02:16
    import { useRouter } from 'next/router';
    
    function componentName() {
        const router = useRouter();
        console.log('router obj', router);
    }
    

    We can find the query object inside a router using which we can get all query string parameters.

    0 讨论(0)
  • 2020-12-13 02:21

    For those looking for a solution that works with static exports, try the solution listed here: https://github.com/zeit/next.js/issues/4804#issuecomment-460754433

    In a nutshell, router.query works only with SSR applications, but router.asPath still works.

    So can either configure the query pre-export in next.config.js with exportPathMap (not dynamic):

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

    Or use router.asPath and parse the query yourself with a library like 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} />;
      });
    };
    
    0 讨论(0)
  • 2020-12-13 02:26

    Using Next.js 9 or above you can get query parameters:

    With router:

    import { useRouter } from 'next/router'
    
    const Index = () => {
      const router = useRouter()
      const {id} = router.query
    
      return(<div>{id}</div>)
    }
    

    With getInitialProps:

    const Index = ({id}) => {
      return(<div>{id}</div>)
    }
    
    Index.getInitialProps = async ({ query }) => {
      const {id} = query
    
      return {id}
    }
    
    0 讨论(0)
  • 2020-12-13 02:28

    Use router-hook.

    You can use the useRouter hook in any component in your application.

    https://nextjs.org/docs/api-reference/next/router#userouter

    pass Param

    import Link from "next/link";
    
    <Link href={{ pathname: '/search', query: { keyword: 'this way' } }}><a>path</a></Link>
    
    Or
    import Router from 'next/router'
    
    Router.push({
        pathname: '/search',
        query: { keyword: 'this way' },
    })
    

    In Component

    import { useRouter } from 'next/router'
    
    export default () => {
      const router = useRouter()
      console.log(router.query);
    
      ...
    }
    
    0 讨论(0)
提交回复
热议问题