[英]NextJS initial state is not updating when routing to same page with different params
This project is using NextJS
这个项目正在使用
NextJS
I have a page which URL looks like this我有一个页面,其中 URL 看起来像这样
localhost:3000/first/second
I call getInitialProps
on that page.我在该页面上调用
getInitialProps
。 Data is passed from getInitialProps
to the component as it should be and I am setting initial state with that data like this数据按原样从
getInitialProps
传递到组件,我正在使用这样的数据设置初始 state
const Index = ({ data }) => {
const [state, setState] = useState(data.results)
}
Now when I send the user to现在,当我将用户发送到
localhost:3000/first/third
getInitialprops
is called as it should be. getInitialprops
被调用,因为它应该是。 data
, that is a parameter of component, is always populated with the latest results from getInitialProps
but state
isn't. data
是组件的一个参数,始终填充来自getInitialProps
的最新结果,但state
不是。 It is populated with previous data that was in it.它填充了其中的先前数据。 It is not resetting when I am doing client-side routing.
当我进行客户端路由时,它不会重置。 Only when I hard refresh the page.
只有当我硬刷新页面时。
As suggested on NextJS GitHub
I tired adding data.key = data.id
, in ```getInitialProps``,` that is always a different number to force state update but it is not working.正如
NextJS GitHub
所建议的那样,我厌倦了在“getInitialProps”中添加data.key = data.id
,这总是一个不同的数字来强制 state 更新,但它不起作用。
Any info will be useful.任何信息都会很有用。
Thank you for your time:)感谢您的时间:)
When using NextJS, getInitialProps
is called before the page renders only for the first time.使用 NextJS 时,
getInitialProps
仅在页面第一次呈现之前调用。 On subsequent page renders (client side routing), NextJS executes it on the client, but this means that data is not available before page render.在随后的页面渲染(客户端路由)中,NextJS 在客户端执行它,但这意味着在页面渲染之前数据不可用。
For the initial page load, getInitialProps will run on the server only.
对于初始页面加载,getInitialProps 将仅在服务器上运行。 getInitialProps will then run on the client when navigating to a different route via the next/link component or by using next/router.
当通过 next/link 组件或使用 next/router 导航到不同的路由时,getInitialProps 将在客户端上运行。
You would require a useEffect
to sync state:您需要一个
useEffect
来同步 state:
const Index = ({ data }) => {
const [state, setState] = useState(data.results);
useEffect(() => {
setState(data.results);
}, [data]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.