reactjs - 使用来自 mongoDB 的数据反应 setState
问题描述
在我的反应应用程序中,我有一个具有以下结构的数组作为状态:
data: {
nodes: [{ id: 'Harry' }, { id: 'Sally' }, { id: 'Alice' }],
links: [{ source: 'Harry', target: 'Sally' }, { source: 'Harry', target: 'Alice' }]
}
数据最初是空的。我想要做的是使用从我的 mongoDB 检索到的数据来设置数据状态。来自数据库的 JSON 示例如下:
{
"_id": {
"$oid": "5c3a368dfb6fc0600bdedf49"
},
"nodes": [
{
"id": "root"
},
{
"id": "input"
},
{
"id": "component"
}
],
"links": [
{
"source": "component",
"target": "root"
},
{
"source": "input",
"target": "root"
}
]
}
在我的反应应用程序的 componentDidMount() 中,我使用以下代码获取数据
fetch('link')
.then(data => json())
.then((res) => {
if (!res.success) this.setState({error: res.error});
else console.log(res.data);
}
});
最后,这是我从 console.log 得到的:
[…]
0: {…}
_id: "5c3a368dfb6fc0600bdedf49"
links: (2) […]
0: Object { source: "component", target: "root" }
1: Object { source: "input", target: "root" }
length: 2
<prototype>: Array []
nodes: (3) […]
0: Object { id: "root" }
1: Object { id: "input" }
2: Object { id: "component" }
length: 3
<prototype>: Array []
<prototype>: Object { … }
length: 1
所以,我还没有弄清楚如何用这些数据设置状态,并将其置于具有适当结构的数据状态中。任何建议都会有所帮助,谢谢!
解决方案
后端总是会返回links
和nodes
数组吗?
如果是,您可以这样做:
this.setState({
data: {
nodes: res.data.nodes,
links: res.data.links,
}
});
如果没有,您必须检查是否从 api 调用返回节点或链接,并仅针对已返回的数据分别更新状态。
推荐阅读
- javascript - Chrome 扩展程序上的桌面通知不起作用
- r - 用`-`符号重命名R中的列
- django - Django rest - 如何序列化预取相关集?
- java - Sonarqube 7.6 无法使用 Gradle 插件加载组件类 org.sonar.plugins.checkstyle.CheckstyleExecutor
- mysql - 无法安装 MySQL 连接器库
- python-3.x - 无法将带有 csv 扩展名的文件从 pandas 写入 AWS S3
- dart - 如何在 Flutter 中实现多个本地通知?
- azure-cosmosdb - CosmosDB 中的逻辑分区扫描是否总是以相同的顺序返回项目?
- apache-spark - 使用 mesos 的火花集群
- vb.net - 如何从交叉表创建 Crystal Reports 折线图