我如何从后端获得特定id的数据在react js?



我试图从后端获得一个特定的id相关数据,而不是整个数据库,然后比较id。我正在使用状态参数传递id。我是新手,所以尽可能简单地解释一下会很有帮助。

这是我获取数据的服务

import http from "./http";
const getBoxes = () => {
return http
.get("/box/getAllBox")
.then((result) =>
result.data.content.map((item, index) => ({ ...item, key: index }))
);
};

您可以通过使用filter()属性轻松地做到这一点

例如

import http from "./http";
const getBoxes = () => {
return http
.get("/box/getAllBox")
.then(result=>{
result.data.content.filter(item=> item.id=="your ID")
})
.then((result) =>
result.data.content.map((item, index) => ({ ...item, key: index }))
);
};

your ID替换为自定义id

您应该创建一个后端端点(如果可能的话),在那里您可以获得一个盒子。例如/盒/{id}。

这意味着当你在react中得到这个端点时,你可以执行result.data。{返回对象中的某些属性}例如result.data.boxName

如果您无法更改后端,您可以通过循环遍历结果并查找返回对象的id与您正在查找的id匹配的位置来从框数组中获得特定的id -这要求返回给每个对象的对象数组包含一个id字段。

import http from "./http";
const getBoxes = () => {
return http
.get("/box/getAllBox")
.then((result) =>
let itemFromID;
for(let i = 0; i < result.data.length; i++) {
let item = result.data[i];
if(item.id === 1) {
itemFromID = item;
break;
}
}
// now you have the item in itemFromID variable
console.log(itemFromID);
);
};

最新更新