如何获取global.window.localstorage Inside getServersideProps
我有一些组件,可以通过数据获取道具并渲染数据。在我的getServersideProps
函数中,我需要从localstorage
获得数据,但是由于window
is undefined 。
我尝试使用if(typeof window!=='undefined')
,但它仍然不起作用。我的代码怎么了?
const MainComponent = ({serverResponseData}) => {
// ... some code
console.log(serverResponseData))
// ... some code
}
export async function getServerSideProps() {
let filterId = []
if (typeof window !== 'undefined') {
filterId = global.window?.localStorage.getItem('filterId') || '';
}
// ...some code, and filterId variable still empty array
const scoresRes = await fetchData('scores',{filterId});
return {
props: {scoresRes}
};
}
我也尝试使用使用效果,但出错
React Hook“ useffect”在函数“ getServersideprops”中称为 既不是React功能组件,也不是自定义React Hook 功能。
I have some component which get props with data and render it data. In my getServerSideProps
function I need to get data from localStorage
, but I can't do it because of window
is undefined
.
I tried using if (typeof window !== 'undefined')
but it's still not working. What's wrong with my code?
const MainComponent = ({serverResponseData}) => {
// ... some code
console.log(serverResponseData))
// ... some code
}
export async function getServerSideProps() {
let filterId = []
if (typeof window !== 'undefined') {
filterId = global.window?.localStorage.getItem('filterId') || '';
}
// ...some code, and filterId variable still empty array
const scoresRes = await fetchData('scores',{filterId});
return {
props: {scoresRes}
};
}
I'm also tried use useEffect, but got error
React Hook "useEffect" is called in function "getServerSideProps" that
is neither a React function component nor a custom React Hook
function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
参考 documentation
localStorage仅在客户端上可用,并且您正在尝试仅在服务器端函数中访问它,您可以使用诸如
请访问
另一种方法是使用 dynamigic import Hello3组件将包含访问本地存储的代码。
Referring to the documentation
Localstorage is only available on the client side and you are trying to access it in a server side only function , you can use something like
Please review this article to get more information on running client side only code.
Another approach would be to use a dynamic import where the hello3 component would contain the code accessing local storage.
getserverserversideprops
仅在服务器端触发,并且在客户端无法使用如果您想拥有该存储逻辑,我建议您改用cookie。不像LocalStorage,服务器端和客户端都可以使用Cookie。
来修改逻辑
您可以使用cookie的另一种可能的方法 ,是使用
getInitialProps
双方都可以使用getServerSideProps
only trigger on the server-side and it won't be available on the client-sideIf you want to have that storage logic, I'd suggest you use cookies instead. Not like localStorage, cookies are available on both server-side and client-side.
You can modify your logic like below with cookies
Another possible approach is using
getInitialProps
which is available on both sides