【发布时间】:2020-06-12 03:11:30
【问题描述】:
我无法以 JSON 格式获取数组数据。 我使用 node.js 发送 json 文件,代码如下。
const express = require("express");
const router = express.Router(); // 라우터 분리
router.get("/api/hello", (req, res) => {
// app 대신 router에 연결
res.json({ express: "hello~" });
});
router.get("/api/beef", (req, res) => {
res.json();
});
module.exports = router; // 모듈로 만드는 부분
而我用json发送的数据是这样的。
{
"test": "Beef data get Completed",
"name": "beef",
"data": [
{ "productName": "양지", "price": 20000 },
{ "productName": "갈비", "price": 30000 },
{ "productName": "등심", "price": 15000 }
]
}
]
然后我使用 fetch 获取数据,并将其保存在 state 中。 我在 fetch 函数中获得了我想要的正确数据,但是当我尝试从 fetch 函数中获取数据时,我不断收到错误消息,例如 cannot get the property blahblahblah... 这是我在客户端做的代码。
import React, { Component } from "react";
const itemList = ["돼지고기", "소고기", "닭&오리", "Sale", "연락처"];
class Contents extends Component {
state = {
parsedJson : "",
};
componentDidMount() {
this._callAPI()
.then(parsedJson=>{
console.log("In the fetch : ",parsedJson[0].data[0])
this.setState({
parsedJson
})
})
.catch(error => {
console.log(error);
this.setState({
...this.state,
isError: true
});
});
}
_callAPI = async () => {
const response = await fetch(`api/${this.props.curPage}`);
const data = response.json();
if (response.status !== 200) throw Error(data.message);
return data;
};
render() {
const stateData = this.state;
console.log("In the render : ",stateData.parsedJson[0].data[0]) <- !!!!!!!!!!!! where error occur
return (
<>
<RenderByItemList
curPage={this.props.curPage}
data={stateData.productData}
/>
</>
);
}
}
【问题讨论】: