问题
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);
What exactly does the getInitialProps method in NextJS?
回答1:
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.
It can run both on the server and on the browser(if you use Link for example).
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.
Docs: https://nextjs.org/learn/basics/fetching-data-for-pages
回答2:
Notice that to load data when the page loads, we use getInitialProps which is an async static method. It can asynchronously fetch anything that resolves to a JavaScript plain Object, which populates props.
Data returned from getInitialProps is serialized when server rendering, similar to a JSON.stringify. Make sure the returned object from getInitialProps is a plain Object and not using Date, Map or Set.
For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.
Note: getInitialProps can not be used in children components. Only in pages.
回答3:
Motivation for using getInitialProps:
All of these answers are correct, but I would like to add that NextJS does server-side rendering. Which means that if you want to fetch data before showing the user something you can't use componentDidMount (because that happens after rendering).
So you need to use getInitialProps because it is executed first, and after that NextJS is rendering the page.
Then NextJS takes the component's HTML that is produced and sends it to the browser.
回答4:
"getIntialProps" is usually used to fetch data from server. It runs on server and client both but with one basic difference ie: to make it work on client side the route has to be hit either from "router.push(/routename)" or by next js 'Link ' component.
All this data can be returned to component in from of props.
Note: "getIntialProps" does not have access to application props.
回答5:
getInitialProps is used when you would like your page to request data on server-side instead of client-side, it allows to take advantage of SEO.
来源:https://stackoverflow.com/questions/52136824/nextjs-getinitialprops-method