【发布时间】: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