Next.js - 理解 getInitialProps

red*_* 87 9 javascript reactjs isomorphic-javascript graphql next.js

我有一个使用 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;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

red*_* 87 7

答案是不

如果您将 Apollo 与 Next JS 一起使用getInitialProps,您将不必在每个页面上使用来获取服务器端呈现的一些初始数据。getInitialProps如果它们中有<Query>组件,以下配置足以让所有组件使用各自的查询进行渲染

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 };
  }
Run Code Online (Sandbox Code Playgroud)

我的问题以及为什么我没有看到任何服务器端渲染是 Heroku 或 Now 不会使用公共 URL 执行 SSR,即 my-app.heroku.com。为了解决这个问题,我在 Heroku 中购买并应用了一个自定义 URL,它起作用了。除了自定义 URL 外,我的 Apollo 配置中还有以下配置

  const request = (operation) => {
    operation.setContext({
      fetchOptions: {
        credentials: 'include'
      },
      headers: { cookie: headers.cookie }
    });
  }; 
Run Code Online (Sandbox Code Playgroud)

这完全解决了它,现在我有了 SSR 而不必getInitialProps在每个页面上手动设置

希望这有助于某人