【问题标题】:Using getInitialProps gives TypeError: Cannot read property 'map' of undefined使用 getInitialProps 给出 TypeError: Cannot read property 'map' of undefined
【发布时间】:2020-08-19 22:09:10
【问题描述】:

我看到了很多与 getInitialProps 和 getStaticProps 相关的问题,但我自己都无法解决。

我只是想加载一些 json 数据(我 console.logged 它并知道它不是未定义的)并将其传递给我的 Main 组件:

import Card from "./components/Card";
import data from "../data/data.json";

const Main = ({ cards }) => {
  return (
      <div}>
        {cards.map((card) => {
          <Card key={card.id} card={card} />;
        })}
      </div>

  );
};

Main.getInitialProps = async (context) => {
  return {
    props: { cards: data },
  };
};

export default Main;

TypeError: 无法读取未定义的属性“地图”

我也试过getStaticProps,同样的问题。

我做错了什么?

【问题讨论】:

  • 您省略了data 的来源,我假设为简单起见。确保它实际上是一个数组。

标签: reactjs next.js


【解决方案1】:

根据the docs,这应该可以:

import Card from "./components/Card";
import data from "../data/data.json";

const Main = ({ cards }) => {
  return (
      <div}>
        {cards.map((card) => {
          <Card key={card.id} card={card} />;
        })}
      </div>

  );
};

Main.getInitialProps = async (context) => {
  // await for `data`

  return {
    cards: data,
  };
  // ^-- note the change, you nested your object inside a `props` property
};

export default Main;

【讨论】:

    【解决方案2】:
    Page.getInitialProps = async (ctx) => {
      const res = await fetch('https://api.url.com')
      const json = await res.json()
      return { stars: json.stargazers_count }
    }
    

    你必须改变它

    return {
        props: { cards: data },
      };
    

    应该使用这个:

    return { cards: data  }
    

    想看更多:docs

    【讨论】:

    • 两天前你的回答和我的有什么不同?
    猜你喜欢
    • 2023-02-22
    • 2018-05-26
    • 1970-01-01
    • 2020-01-21
    • 2021-06-25
    • 2017-08-19
    • 2017-04-24
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多