NextJS:getInitialProps 方法 [英] NextJS: getInitialProps method

查看:73
本文介绍了NextJS:getInitialProps 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 NextJS 并看到一个页面示例:

Working with NextJS and saw an example of a page:

class IndexPage extends Component {
  static async getInitialProps(context) {
    return {};
  }
  render() {
    return <div>hello world</div>;
  }
}
export default withRouter(IndexPage);

NextJS 中的 getInitialProps 方法究竟是什么?

What exactly does the getInitialProps method in NextJS?

推荐答案

getInitialProps 通常是一个适用于服务器上的异步操作,然后将数据作为道具传递给页面.

getInitialProps is usually an async function which is good for asynchronous operations at the server and then it passes data to the page as props.

它可以在服务器和浏览器上运行(例如,如果你使用Link).

It can run both on the server and on the browser(if you use Link for example).

我的结论是,当您的组件充当 Page 并且您希望将数据作为 Props 提供时,使用 getInitialProps 来获取数据.

My conclusion would be to use getInitialProps to fetch data when your component acts as a Page, and you want to provide the data as Props.

文档:https://nextjs.org/learn/basics/fetching-页面数据

这篇关于NextJS:getInitialProps 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆