问题
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 /about?name=leangchhean) from /index.js
to /about.js
, I don't know how to get it in /about.js
page.
index.js
import Link from 'next/link'
export default () => (
<div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)
回答1:
Get it by using below code in the about.js page:
// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
<p>Welcome to About! { name }</p>
)
回答2:
url
prop is deprecated as Next.js version 6:
https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md
To get the query params, 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}
回答3:
How about use router-hook?
you can use the useRouter hook
in any component in your app.
https://github.com/zeit/next.js/#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);
...
}
回答4:
For those looking for a solution that works with static exports, try solution listed here: https://github.com/zeit/next.js/issues/4804#issuecomment-460754433
In a nutshell, router.query
works only with SSR apps, 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} />;
});
};
来源:https://stackoverflow.com/questions/43862600/how-to-get-query-string-parameters-from-url-in-next-js