为什么数据未显示在nextjs中?

时间:2020-01-08 11:14:05

标签: reactjs next.js server-side-rendering next

我正在制作一个非常简单的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;

因此,按照上面给定的代码,我在layout页面内调用了index.js页面(在我的实际应用程序中,我只需要这样调用,因此在索引内调用布局不会发生变化)。

但是,当我在布局中的函数console.log()中创建了Layout.getInitialProps时,它什么也不会打印,因此不会获取api数据。

Complete working demo here with code

为什么当我从layout.js的孩子那里打电话时,无法在index.js内部获取数据?

还为我提供了正确的更新解决方案以实现此目标。.我确实搜索了许多问题,但没有一个解决了我的问题,并且我无法清楚地理解这些解决方案,因此请使用上面给出的示例帮助我。

1 个答案:

答案 0 :(得分:1)

因为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,带有类组件
奖励:如果您想为应用的所有页面添加布局,这不是最好的方法,而是应该看看custom _app.jsexample < / p>