NextJS 中从未调用过 getInitialProps
getInitialProps in never called in NextJS
我对 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
个页面和 REST
个页面完全不同
此问题已通过 https://github.com/zeit/next.js/tree/canary/examples/with-apollo
上的文档解决
问题是我将整个 _app
包装在 Apollo
提供商中,正确的方法是只包装需要 Apollo
的页面。
其他需要getInitialProps
的应该保持原样并在其中调用REST API
。
我对 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
个页面和 REST
个页面完全不同
此问题已通过 https://github.com/zeit/next.js/tree/canary/examples/with-apollo
上的文档解决问题是我将整个 _app
包装在 Apollo
提供商中,正确的方法是只包装需要 Apollo
的页面。
其他需要getInitialProps
的应该保持原样并在其中调用REST API
。