亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Next.js - 理解 getInitialProps

Next.js - 理解 getInitialProps

Qyouu 2021-06-02 17:46:09
我有一個使用 next.js 和 Apollo/Graphql 的應用程序,我正在嘗試完全了解getInitialProps生命周期掛鉤的工作原理。getInitialProps在我的理解中,生命周期用于設置一些初始道具,這些道具將在應用程序首次加載時呈現服務器端,可以使用從數據庫中預取數據以幫助 SEO 或只是為了提高頁面加載時間。我的問題是這樣的:每次我有一個query組件在我的應用程序中獲取組件中的一些數據時,我是否必須使用getInitialProps以確保數據將在服務器端呈現?我的理解也是getInitialProps它只適用于頁面索引組件(以及在 中_app.js),這意味著組件樹中較低的任何組件都無法訪問此生命周期,并且需要從上往下獲取一些初始道具在頁面級別,然后讓它們向下傳遞組件樹。(如果有人能證實這個假設會很棒)這是我的代碼:_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;
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 363 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號