问题
I have a dynamic page with a dynamic url. everything is clientside rendered.
This is the link
that links to the second page
<Link
href= {{ pathname: '/dashboard/[orderdetail]', query: { id: `${orderID}` } }} as={`/dashboard/${orderDetails.orderNo}`}
</Link>
This works well taking every query to the second page. But when I refresh the second page, everything is lost. Every query i had passed is lost
I have tried using with/Router
let orderID=this.props.router.query.orderdetail;
Still on page refresh everything is lost.
I need the query string
i am passing to the second page to make a call to a database which works well. But again, when I refresh the page nothing works.
How can I avoid this loss when the page refreshes.
回答1:
In the end I ended up with this solution, there is no difference here
<Link
href={{
pathname: "/dashboard/" + `${orderDetails.orderNo}`,
query: { id: `${orderID}` },
}} as={`/dashboard/${orderDetails.orderNo}`}
>
</Link>
but adding this in the second page somehow maintains the route query.
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
};
}
How this solves the problem, I don't know, but it does. I do not think there will be that much difference considering I only wanted client-side rendering
回答2:
Looks like there is some confusion about what query parameters you are working with.
With the href
URL object you have in your example the resulting full href URL will be:
/dashboard/[order]?id=nnn
so router.query
will contain an order
key and an id
key, but no orderdetail
.
The order
key will be set to the content of orderDetails.orderNo
with your given as
property, but the id
will not be set since as
has no ?id=xxx
part.
Assuming your JS filename is /pages/dashboard/[order].js
, your ${orderDetails.orderNo} is accessible as this.props.router.query.order
and the id
query string is never used.
this.props.router.query.orderdetail
as in your code from the question will never be set to anything since the request has no such parameter name.
If instead the filename is /pages/dashboard/[orderdetail].js
you need the corresponding
<Link href="/dashboard/[orderdetail]" as={`/dashboard/${orderDetails.orderNo}`}>...</Link>
来源:https://stackoverflow.com/questions/61891845/is-there-a-way-to-keep-router-query-on-page-refresh-in-nextjs