简体   繁体   English

使用NextJs在儿童中调用getInitialProps

[英]Calling getInitialProps in children using NextJs

I am implementing data fetching in Next.js using this example: 我正在使用此示例在Next.js中实现数据获取:

https://github.com/zeit/next.js/blob/master/examples/data-fetch/pages/index.js https://github.com/zeit/next.js/blob/master/examples/data-fetch/pages/index.js

I first tried it by adding the getInitialProps bit in one of my components but it does not get called unless I put it in one of the main pages. 我首先通过在我的一个组件中添加getInitialProps位来进行尝试,但是除非将其放在主页之一中,否则它不会被调用。 I read some somewhat related discussions that I may need to call the children's getInitialProps from the pages/parent getInitialProps but not clear on how to do so. 我阅读了一些相关的讨论,可能需要从页面/父级getInitialProps调用子级的getInitialProps ,但不清楚如何执行。 Also I am wondering if perhaps I should keep the call in the page itself as far as proper technique. 我也想知道是否应该将呼叫保留在页面本身中,以适当的技术为限。

Ah.. right from he NextJS docs :) 嗯..从他的NextJS文档开始:)

Note: getInitialProps can not be used in children components. 注意:getInitialProps不能在子组件中使用。 Only in pages. 仅在页面中。

You need to use higher order components (HOC). 您需要使用高阶组件(HOC)。 page as children of HOC. 页面作为HOC的子级。 You can call getInitialProps from HOC and as well as from page. 您可以从HOC和页面调用getInitialProps

Here is an example: https://github.com/zeit/next.js/tree/canary/examples/with-higher-order-component 这是一个示例: https : //github.com/zeit/next.js/tree/canary/examples/with-higher-order-component

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM