为什么数据没有显示在 nextjs 中?

Why the data not displayed in nextjs?

我正在制作一个非常非常简单的 nextjs 应用程序,我试图从中获取数据 api。

我的要求是我应该在 layout.js 文件中显示数据,并且这个 layout.js 文件是 index.js 文件中的子文件。

index.js:

import Layout from "./layout";
import React from "react";

class Home extends React.Component {
  render() {
    return (
      <div>
        <Layout />
        <h4> Main content will be displayed here !! </h4>
      </div>
    );
  }
}

export default Home;

layout.js:

import React from "react";
import fetch from "isomorphic-unfetch";

function Layout(props) {
  return (
    <div>
      <p>Preact has {props.stars} ⭐</p>
      <p> Why I couldn't get the above "props.star" ? </p>
    </div>
  );
}

Layout.getInitialProps = async () => {
  console.log("comes into layout getinitial props");
  const res = await fetch("https://api.github.com/repos/developit/preact");
  const json = await res.json(); // better use it inside try .. catch
  return { stars: json.stargazers_count };
};

export default Layout;

因此,根据上面给出的代码,我在 index.js 页面中调用了 layout 页面(在我的实际应用程序中,我只需要这样调用,因此在索引内部调用布局没有变化)..

但是当我在布局中的函数 Layout.getInitialProps 中创建 console.log() 时,它不打印任何内容,因此未获取 api 数据..

Complete working demo here with code

为什么我无法从 index.js 调用时获取 layout.js 中的数据?

还为我提供了正确的更新解决方案来实现这一点。我确实搜索了很多问题,但 none 解决了我的问题,但我无法清楚地理解这些解决方案,所以请帮助我解决上面给出的示例.

那是因为getInitialProps只能添加到页面导出的默认组件中,添加到其他任何组件都不起作用。
您应该改用 componentDidMount()useEffect,或者在索引中移动 getInitialProps,然后将结果传递给组件。类似(未测试):

index.js :

import Layout from "./layout";
import React from "react";

class Home extends React.Component {
  render() {
    return (
      <div>
        <Layout />
        <h4> Main content will be displayed here !! </h4>
      </div>
    );
  }
}

export default Home;

layout.js

import React from "react";
import fetch from "isomorphic-unfetch";
class Layout extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      stars: false
    };
  }
  async componentDidMount() {
    console.log("comes into layout getinitial props");
    const res = await fetch("https://api.github.com/repos/developit/preact");
    const json = await res.json(); // better use it inside try .. catch
    this.setState({ stars: json.stargazers_count });
  }
  render() {
    const { stars } = this.state;
    return (
      <div>
        <p>Preact has {stars} ⭐</p>
        <p> Why I couldn't get the above "props.star" ? </p>
      </div>
    );
  }
}

export default Layout;

编辑: Example 与 class 组件
奖励: 如果您想为应用的所有页面添加布局,这不是最佳方法,您应该查看 custom _app.js, example