问题描述
使用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 forasynchronous 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).
我的结论是,当您的组件充当页面,并且您希望将数据作为道具提供时,使用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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!