为什么nextjs中没有显示数据? [英] Why the data not displayed in nextjs?

查看:12
本文介绍了为什么nextjs中没有显示数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

index.js:

从./layout"导入布局;从反应"导入反应;类 Home 扩展 React.Component {使成为() {返回 (

<布局/><h4>主要内容会在这里展示!!</h4></div>);}}导出默认主页;

layout.js:

从react"导入反应;从isomorphic-unfetch"导入获取;功能布局(道具){返回 (

<p>Preact 有 {props.stars} ⭐</p><p>为什么我不能得到上面的props.star"?</p></div>);}Layout.getInitialProps = async() =>{console.log("进入布局 getinitial 道具");const res = await fetch("https://api.github.com/repos/developit/preact");常量 json = 等待 res.json();//最好在 try .. catch 中使用它返回{星星:json.stargazers_count};};导出默认布局;

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

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

在这里用代码完成工作演示

为什么我不能从 index.js 作为子级调用时获取 layout.js 内的数据?

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

解决方案

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

index.js:

从./layout"导入布局;从反应"导入反应;类 Home 扩展 React.Component {使成为() {返回 (

<布局/><h4>主要内容会在这里展示!!</h4></div>);}}导出默认主页;

layout.js

从react"导入反应;从isomorphic-unfetch"导入获取;类布局扩展 React.Component {构造函数(道具){超级(道具);这个.state = {星星:假的};}异步组件DidMount() {console.log("进入布局 getinitial 道具");const res = await fetch("https://api.github.com/repos/developit/preact");常量 json = 等待 res.json();//最好在 try .. catch 中使用它this.setState({ stars: json.stargazers_count });}使成为() {常量 { 星星 } = this.state;返回 (

<p>Preact 有 {stars} ⭐</p><p>为什么我不能得到上面的props.star"?</p></div>);}}导出默认布局;

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

I am making a very very simple nextjs application where I am trying to fetch the data from api.

My requirement is I should display the data in layout.js file and this layout.js file is a children in index.js file.

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;

So as per the above given code, I have called the layout page inside index.js page (in my real application I need to call like this only so no changes in calling layout inside index)..

But when I made a console.log() in the function Layout.getInitialProps in layout, it doesn't print anything and hence the api data not fetched..

Complete working demo here with code

Why can't I fetch the data inside the layout.js while calling as a children from index.js?

Also provide me the right updated solution to achieve this.. I really searched for many questions but none solved my issue and I couldn't understand those solutions clearly so please help me with the above given example.

解决方案

That because getInitialProps can only be added to the default component exported by a page, adding it to any other component won't work.
You should use componentDidMount() or useEffect instead, or move getInitialProps in the index and then pass the result to the component. something like (not tested) :

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;

Edit: Example with class component
Bonus: If you want to add the layout for all the pages of your app this isn't the best approach, instead you should take a look to custom _app.js, example

这篇关于为什么nextjs中没有显示数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆