vercel / next.js

The React Framework
https://nextjs.org
MIT License
125.97k stars 26.88k forks source link

Page state is not reset for navigating between dynamic routes #9992

Closed ZigZagT closed 3 years ago

ZigZagT commented 4 years ago

Bug report

Describe the bug

The page state is not reset for navigation between dynamic routes that served by the same source component.

for example, give page source /a/[param]/index.js, when navigating from /a/1 to /a/b, states on the page won't' be reset.

The causing is that for this kind of navigation, what actually happened is the same React Component been rendered with different props. Thus react takes it as a component is rerendering itself, and causing the new navigated page receive stale states.

To fix it, just add {key: <composed base on URL routing params> } to page initial props.

To Reproduce

I've created a live example:

Edit next-bug-dynamic-route-not-rerender

Expected behavior

Page should be fully reloaded and states should be reset.

Screenshots

N/A

System information

Additional context

santsys commented 3 years ago

I've been having this same issue and been able to mostly solve it (in many places) using react key properties on my markup that contain the dynamic route value... For example...

For a route that uses a [lang] property to change language... e.g. /[lang]/page1

<Page key={'page_' + props.lang}>...</Page>

Setting the unique key based on the property seems to let react know to re-render the items... it seems even if the data of the page is different, when there is the same fundamental component, react doesn't know to properly update the components on the page. Figured I'd share what seems to be working for me in a lot of cases.

balazsorban44 commented 2 years ago

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.