首页 > 解决方案 > 使用来自 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

所以,我还没有弄清楚如何用这些数据设置状态,并将其置于具有适当结构的数据状态中。任何建议都会有所帮助,谢谢!

标签: reactjsmongodbgetstate

解决方案


后端总是会返回linksnodes数组吗?
如果是,您可以这样做:

this.setState({
    data: {
        nodes: res.data.nodes,
        links: res.data.links,
    }
});

如果没有,您必须检查是否从 api 调用返回节点或链接,并仅针对已返回的数据分别更新状态。


推荐阅读