如何使用函数组件在react中基于另一个列表向json列表添加新属性?



有点JavaScript/react新手。

只是在基本的react/JavaScript语法上有点卡住这就是我想要达到的目标:

import axios from 'axios';
import React, { useState, useEffect, useMemo } from "react";
const testCombineApi = () => {
const [assocs, setAssocs] = useState([])
const [loadingData, setLoadingData] = useState([])
const [corenodes, setCoreNodes] = useState([])
const projectId = 1

/// i can probably combine both calls? with another then?
useEffect(() => {
async function getData() {
await axios
.get(`/api/.../`)
.then((response) => {
console.log(response.data);
setCoreNodes(response.data)
setLoadingData(false);
});
}
if (loadingData) {
getData();
}
}, []);
useEffect(() => {
async function getData() {
await axios
.get(`/api/.../${projectId}/`)
.then((response) => {
console.log(response.data);
setAssocs(response.data)
setLoadingData(false);
});
}
if (loadingData) {
getData();
}
}, []);
// Trying to add the property "withproject" to every json in the list corenodes
const initnodes = setCoreNodes({
...corenodes, 
withproject: false
})
//this is the part i just to combine the two pieces of info
// i usually use python, so what i want to do would be 
// for node in nodes:
//     node.withproject = True
// for assoc in assocs:
//     targetId = assoc.id
//     for node in nodes:
//         if targetId = node.id:
//             node.withproject = False

const testing123 = assocs =>  {
initnodes
for (let i=0; i < assocs.length; i++) {
let id = assocs[i].id
for (let j = 0; j < corenodes.length; j++) {
let nodeId = corenodes[j].id  
{id == nodeId &&
setCoreNodes({...corenodes, [corenodes[j].withproject]: false})   
}
}
}
console.log(corenodes)
}
return(
<ul> {testing123(assocs)} </ul>
)
}
export default testCombineApi

我已经将我的代码包含在评论中,就像我想要实现的一样。不过为了方便阅读,我还是把它放在这里

for node in nodes:
node.withproject = True
for assoc in assocs:
targetId = assoc.id
for node in nodes:
if targetId = node.id:
node.withproject = False

我试图添加一个额外的列,最终将被渲染为一个表中的复选框,然后我可以使用它来通过API更新我的DB

这是node JSON的样子

[
{
"id": 263,
"hostname": "qwer123",
"serial": "",
},
{
"id": 264,
"hostname": "asdf123",
"serial": "",
},
]

和我用特定的{$projectID}

查询API时得到的结果基本相同这在反应中是合理的吗?或者我必须调整我的思维方式才能让它工作??

提前感谢!

好了,让我们稍微改变一下视角!"response.data"不是JSON,而是JS对象的集合(列表)。在JS中,你有一个循环遍历整个集合的函数,允许你使用箭头函数来转换对象。

在你的例子中:

const initnodes = setCoreNodes({
...corenodes, 
withproject: false
})

可以改成:

const coreNodeModels = corenodes
.map(coreNode => {

// this will create a new object 
return { 
withProject: false,
...coreNode // this will copy all properties from the coreNode object
}
})

在此之后,你将有一个与coreNode不同类型的coreNodeModel的集合,因此将它们存储在不同的"useState"状态。

我希望我对你有所帮助,也看看typescript,它一开始更容易理解,它不会让你混淆类型。

干杯!

最新更新