next js getInitialProps 错误 Cannot read 属性 'map' of undefined

next js getInitialProps error Cannot read property 'map' of undefined

我有一个无法读取 属性 'map' 未定义类型错误的错误 我想在映射菜单后显示 menus.name 列表。 我不明白这个错误

这是我的 ssr-test.js 代码

import Layout from "../components/Layout";
import axios from "axios";

export default class SSRTest extends React.Component {
  static async getInitialProps({ req }) {
    const response = await axios.get("http://localhost:9000/menus");
    return { menus: response.data };
  }
  render() {
    const { menus } = this.props;
    const menuList = menus.map(menu => <li key={menu.id}>{menu.name}</li>);
    return <ul>{menuList}</ul>;
  }
}

接下来是我的db.json代码

{
    "menus": [{
            "id": 1,
            "name": "연어",
            "picture": 123,
            "caption": "존맛탱",
            "url": 123
        },
        {
            "id": 2,
            "name": "돈까쓰",
            "picture": 123,
            "caption": "존맛탱",
            "url": 123
        },
        {
            "id": 3,
            "name": "김치볶음밥",
            "picture": 123,
            "caption": "존맛탱",
            "url": 123
        }
    ]
}

这是错误代码..

Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
    at SSRTest.render (pages/ssr-test.js:11:0)
    at finishClassComponent (node_modules/react-dom/cjs/react-dom.development.js:13537:0)
    at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:13500:0)
    at beginWork (node_modules/react-dom/cjs/react-dom.development.js:14089:0)
    at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:16415:0)
    at workLoop (node_modules/react-dom/cjs/react-dom.development.js:16453:0)
    at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:16532:0)
    at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:17386:0)
    at performWork (node_modules/react-dom/cjs/react-dom.development.js:17294:0)
    at performSyncWork (node_modules/react-dom/cjs/react-dom.development.js:17266:0)

首先检查您的提取是否一切正常 url 并且您的请求有效。 其次,您应该将响应数据提取到一个深度,因为您分配的是一个对象而不是数据数组。

  static async getInitialProps({ req }) {
      const response = await axios.get("http://localhost:9000/menus");
      return { menus: response.data.menus };
  }

过去几天我一直遇到同样的问题,根据我的经验,我认为由于 getInitialProps() 函数中有对外部资源的请求,它 returns 一个未解决的 javascript 对象。

当我们直接尝试使用对象内部的数据时,它起作用了。但是 .map() 不起作用。

注意: 将数据打印到控制台时:

初始状态


A​​fter Expanding(蓝色'i'表示数据是在展开后计算的),因此我们无法在.map()中使用它