gpt4 book ai didi

javascript - next js getInitialProps错误无法读取未定义的属性 'map'

转载 作者:行者123 更新时间:2023-12-03 01:07:05 24 4
gpt4 key购买 nike

我遇到一个错误,无法读取未定义 TypeError 的属性“map”我想在映射菜单后显示menu.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)

最佳答案

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

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

关于javascript - next js getInitialProps错误无法读取未定义的属性 'map',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com