[英]NextJS: Get data from local storage in getInitialProps method
I try to migrate my project to Next.js
framework for having SSR (Server side rendering) feature.我尝试将我的项目迁移到
Next.js
框架以获得 SSR(服务器端渲染)功能。 Here is my simple page:这是我的简单页面:
class Example extends React.Component {
static getInitialProps() {
// api getting data. Need authentication data under local storage
}
render() {
return <div>{this.props.data}</div>;
}
}
The problem I met is: I want my data is from getInitialProps
first (that is the purpose of SSR).我遇到的问题是:我希望我的数据首先来自
getInitialProps
(这就是 SSR 的目的)。 But when sending, I need a information about user for backend API.但是在发送时,我需要有关后端 API 的用户信息。 But at this function, rendering is happened on server so I cannot get data from local storage.
但是在这个函数中,渲染发生在服务器上,所以我无法从本地存储中获取数据。 How can you solve this problem.
你怎么能解决这个问题。
Thanks谢谢
You can put the call to localStorage
into a react component lifecycle method such as componentDidMount
and then setState()
with the result.您可以将调用
localStorage
放入反应组件生命周期方法中,例如componentDidMount
,然后将结果设置为setState()
。
It's not great, but will work.这不是很好,但会起作用。
Note that this would obviously not use SSR.请注意,这显然不会使用 SSR。
This works for me:这对我有用:
const USER = 'user'
const URL = 'http://www.example.com/user'
// here you can also use isServer
if (req) {
const {data: user} = await Axios.get(URL)
localStorage.setItem(USER, JSON.stringify(user))
} else {
const user = await JSON.parse(localStorage.getItem(USER))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.