首页 > 解决方案 > 为什么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;

布局.js

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

function Layout(props) {
  return (
    <div>
      <p>Preact has {props.stars} ⭐&lt;/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 数据..

在此处使用代码完成工作演示

为什么我不能在layout.js作为孩子调用的时候从里面获取数据index.js

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

标签: reactjsnext.jsserver-side-rendering

解决方案


那是因为 getInitialProps只能添加到页面导出的默认组件中,将其添加到任何其他组件都不起作用。
您应该使用componentDidMount()oruseEffect代替,或者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;

布局.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} ⭐&lt;/p>
        <p> Why I couldn't get the above "props.star" ? </p>
      </div>
    );
  }
}

export default Layout;

编辑: 带有类组件的示例
奖励:如果您想为应用程序的所有页面添加布局,这不是最好的方法,相反您应该查看自定义 _app.js示例


推荐阅读