简体   繁体   English

NextJS:在 getInitialProps 方法中从本地存储获取数据

[英]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.

相关问题 NextJS:getInitialProps 方法 - NextJS: getInitialProps method 如何使用 redux-saga 在 getInitialProps 中获取数据。然后在 getInitialProps 方法中从 redux store 获取响应? - How to fetch data in getInitialProps with redux-saga.Then get the response from redux store while in the getInitialProps method? 使用NextJS对Class Components和getInitialProps做SSR,render方法有未定义数据 - Using NextJS to do SSR with Class Components and getInitialProps, render method has undefined data NextJS:如何将数据从一页发送到另一页的getInitialProps函数 - NextJS: How to send data from one page to another page's getInitialProps function Next.js 中的 getInitialProps 不从服务器获取数据 - getInitialProps in Next.js does not get data from server Nextjs App如何在使用Firestore查询后处理本地数据存储? - Nextjs App how to handle local data storage after querying with Firestore? Nextjs getInitialProps无法与NGINX一起使用 - Nextjs getInitialProps not working with NGINX 使用 react/nextjs 中本地存储的参数初始化组件 - Initializing component with parameter from local storage in react/nextjs getStaticProps 不适用于 Nextjs 中的 getInitialProps - getStaticProps not working with getInitialProps in Nextjs 从 getInitialProps 使用 localstorage 或 cookie 和 Apollo 验证 Nextjs 网站 - Auth Nextjs website from getInitialProps with localstorage or cookie and Apollo
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM