【问题标题】:getInitialProps in never called in NextJS在 NextJS 中从未调用过 getInitialProps
【发布时间】:2020-07-13 01:30:19
【问题描述】:

我对 NextJS 中的 getInitialProps 方法有疑问。它永远不会被调用。在这个项目中,我有一些页面的Apollo GraphQL 客户端和其他页面的getInitialProps。我不确定如何正确配置它们才能工作。

Apollo 工作正常并按应有的方式获取数据。问题是 getInitialProps 没有被调用。

这是我自定义的_app.js 文件

const App = ({ Component, pageProps, apollo }) => {
  return (
    <ApolloProvider client={apollo}>
      <Component {...pageProps} />
    </ApolloProvider>
  )
}

const API_URL =
  process.env.NODE_ENV === "development"
    ? "http://localhost/wordpress/index.php?graphql"
    : "https://page/index.php?graphql"

export default withApollo(({ initialState }) => {
  return new ApolloClient({
    link: new createHttpLink({
      uri: API_URL,
      fetch: fetch
    }),
    cache: new InMemoryCache()
  })
})(App, { getDataFromTree })

这就是我在页面上如何称呼getInitialProps

Coupons.getInitialProps = async function() {
  const res = await fetch('http://localhost:8000/data/');
  const data = await res.json();

  console.log(`Data fetched. Count: ${data.length}`);

  return {
    shows: data.map(entry => entry.show)
  };
};

还有。我有Apollo 获取数据的页面不需要调用此REST API。 Apollo pages 和 REST pages 完全不同

【问题讨论】:

  • 你能试试const App = ({ Component, pageProps, apolloClient }) 吗?
  • 不行ApolloProvider was not passed a client instance. Make sure you pass in your client via the "client" prop.

标签: graphql next.js react-apollo


【解决方案1】:

此问题已通过 https://github.com/zeit/next.js/tree/canary/examples/with-apollo 上的以下文档修复

问题是我将整个 _app 包装在 Apollo 提供程序中,正确的方法是只包装需要 Apollo 的页面。

其他需要getInitialProps 的人应该保持原样并在其中调用REST API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2021-08-04
    • 2021-11-03
    • 2018-01-05
    • 1970-01-01
    • 2020-06-26
    相关资源
    最近更新 更多