javascript - 使用 React 和 Express 从服务器解析 JSON - “TypeError: Cannot read property '' of undefined”
问题描述
我在客户端代码中解析从服务器返回的 JSON 时遇到问题。如果我向我的 mongoDB 服务器发送基本请求:
GET http://localhost:4000/food/
我得到以下响应,这显然是一个对象数组。
在我的客户端中,我在构造函数中定义了一个状态:
this.state = {
index: 0,
foodList: []
};
还有一个函数 callServer,它在页面加载时调用componentWillMount()
:
callServer() {
fetch("http://localhost:4000/food/")
.then(res => res.json())
.then(res => this.setState({ foodList: res }))
.catch(err => err);
}
此函数使用服务器输出填充文件状态中的 foodList - 当我运行console.log("debug:\n" + JSON.stringify(this.statefoodList[0]))
输出时
Debug:
{"registerDate":"2020-04-01T14:34:04.834Z","_id":"5e66437d59a13ac97c95e9b9","image":"IMAGE","name":"Example 2","address":"BI1 111","type":"ExampleType1","price":"£Example Price","link":"example.com"}
这表明 foodList 被正确设置为服务器的输出。
问题是,如果我执行console.log("debug:\n" + JSON.stringify(this.state.foodList[0].name))
我得到错误TypeError: Cannot read property 'name' of undefined。
我一直在为这个问题苦苦挣扎 - 我不明白为什么客户认为 foodList 是未定义的,而您可以从之前的测试中看到它不是未定义的,并且它是 JSON 格式。
作为旁注,如果它很重要,我会console.log()
从方法内部调用render()
,但在return()
值之前。
我对 React 框架和整个 JS 都很陌生,所以任何帮助将不胜感激:)
解决方案
在使用来自服务器的数据填充数组之前,您尝试console.log
使用数组的第一个元素(因为 ajax 调用需要一些时间来执行),因此 this.state.foodList 的位置 0 仍然未定义。
您可以通过首先检查数组是否具有这样的长度来解决此问题
console.log(this.state.foodList.length && "debug:\n" + JSON.stringify(this.state.foodList[0].name))
推荐阅读
- android - 增加 MaxRecycledViews 对 Recyclerview 性能有影响吗?
- python - 有没有办法确定给定字节数据的格式
- r - 如何提取R中括号内的文本?
- reactjs - 跨域请求被阻止 React Golang
- javascript - 我在设置 Flatlist numColumn >=2 时遇到问题,引发违规错误
- java - 为什么 Optional 继续说我的 List 为空?
- python - 文本文件中的随机词
- python - 当我将其用作继承属性错误时,我的类是“int”,解决方案是什么?
- erlang - Erlang gen_server:如何捕获错误?
- python-3.x - 为用户输入定义一个函数,然后将其分配给另一个定义的函数