node.js - 当我将数据置于状态时无法获取 json 中的数组
问题描述
我无法以 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 函数中获取数据时,我不断收到错误消息,例如无法获取属性 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}
/>
</>
);
}
}
解决方案
在您的组件的第一次渲染中,parsedJson
是字符串,并且stateData.parsedJson[0]
返回一个空字符串,并且空字符串上没有data
属性,因此您会收到错误消息。
为了解决这个问题,你必须在你的渲染方法中写一个 if :
import React, { Component } from "react";
const itemList = ["돼지고기", "소고기", "닭&오리", "Sale", "연락처"];
class Contents extends Component {
state = {
parsedJson: [],
error: null,
};
componentDidMount() {
this._callAPI()
.then(res => {
this.setState({
parsedJson: res[0].data, // here we set state the data array
})
})
.catch(error => {
console.log(error);
this.setState({
...this.state,
error // here we set state occurred error
});
});
}
_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 { parsedJson, error } = this.state;
if (parsedJson && parsedJson.length) {
return <RenderByItemList
curPage={this.props.curPage}
data={parsedJson}
/>
} else {
return !!error || 'loading';
}
}
}
而且最好处理 fetch 操作的加载:
import React, { Component } from "react";
const itemList = ["돼지고기", "소고기", "닭&오리", "Sale", "연락처"];
class Contents extends Component {
state = {
parsedJson: [],
error: null,
loading: false
};
componentDidMount() {
this.setState({
loading: true,
}, () => {
this._callAPI()
.then(res => {
this.setState({
parsedJson: res[0].data, // here we set state the data array
loading: false,
error: null,
})
})
.catch(error => {
console.log(error);
this.setState({
loading: false,
error // here we set state occurred error
});
});
})
}
_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 { parsedJson, error, loading } = this.state;
if (loading) {
return 'loading' // or write a Loading component and render it everywhere
} else if (error) {
return error // or write an Error component
} else {
return (
<RenderByItemList
curPage={this.props.curPage}
data={parsedJson}
/>
);
}
}
}
推荐阅读
- python - 提供带有 send_from_directory() 错误的混合文件名
- docker - 如何根据 pod 名称或容器 ID 查找容器镜像路径
- c# - 如何在 dot net core 2.1 中保持会话活动
- android - Unity中的Android aar
- sql - 将现有的 sql 添加到 django 项目
- julia - @printf 宏使用预定义的格式字符串产生错误
- javascript - 动态循环对象的键
- java - 在 Visual Studio 代码中遇到 launch.json 问题
- swift - 为 CALayer 添加多个遮罩(1 用于添加角)
- excel - 粘贴到excel时数据差异