我有一個使用 next.js 和 Apollo/Graphql 的應(yīng)用程序,我正在嘗試完全了解getInitialProps生命周期掛鉤的工作原理。getInitialProps在我的理解中,生命周期用于設(shè)置一些初始道具,這些道具將在應(yīng)用程序首次加載時呈現(xiàn)服務(wù)器端,可以使用從數(shù)據(jù)庫中預(yù)取數(shù)據(jù)以幫助 SEO 或只是為了提高頁面加載時間。我的問題是這樣的:每次我有一個query組件在我的應(yīng)用程序中獲取組件中的一些數(shù)據(jù)時,我是否必須使用getInitialProps以確保數(shù)據(jù)將在服務(wù)器端呈現(xiàn)?我的理解也是getInitialProps它只適用于頁面索引組件(以及在 中_app.js),這意味著組件樹中較低的任何組件都無法訪問此生命周期,并且需要從上往下獲取一些初始道具在頁面級別,然后讓它們向下傳遞組件樹。(如果有人能證實這個假設(shè)會很棒)這是我的代碼:_app.js(在/pages文件夾中)import App, { Container } from 'next/app';import { ApolloProvider } from 'react-apollo';class AppComponent extends App { static async getInitialProps({ Component, ctx }) { let pageProps = {}; if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } // this exposes the query to the user pageProps.query = ctx.query; return { pageProps }; } render() { const { Component, apollo, pageProps } = this.props; return ( <Container> <ApolloProvider client={apollo}> <Component client={client} {...pageProps} /> </ApolloProvider> </Container> ); }}export default AppComponent;Index.js(在/pages/users文件夾中)import React, { PureComponent } from 'react';import { Query } from 'react-apollo';import gql from 'graphql-tag';const USERS_QUERY = gql` query USERS_QUERY { users { id firstName } }`;class Index extends PureComponent { render() { return ( <Query query={USERS_QUERY}> {({data}) => { return data.map(user => <div>{user.firstName}</div>); }} </Query> ); }}export default Index;
Next.js - 理解 getInitialProps
Qyouu
2021-06-02 17:46:09