我有一个从服务器接收和显示类别的循环。现在我想将每个类别的ID发送到服务器,并返回子类别的数量。我该怎么做呢?
JSX循环:
<tbody>
{maincategorylist.map((maincat, index) => (
<tr key={maincat.id}>
<td>
{maincat.categoryName}
//display count of subcategory
</td>
</tr>
))}
</tbody>
我也写了一个函数,但是我不会使用它。
const handleCount = (id) => {
axios
.get(`Adminbarber/GetCountSubCategories/${id}`, {
headers: {
Authorization: "Bearer " + admintoken,
},
})
.then((res) => {
// setCount(res.data) ;
console.log(res.data);
return res.data;
});
};
我建议创建另一个专门为您处理此功能的组件。它使其可重用,并允许您将子类别计数的数据/组件的生命周期与表和类别的数据/组件分离。
它可能看起来像这样:
function SubcategoryCount(props) {
const { categoryId } = props;
const [subcategoryCount, setSubcategoryCount] = useState(0);
// You'll also want to handle idle, loading, and error states visually
// For example, showing a spinner, or not showing a count until success
// Handles fetching data (though I prefer react-query)
useEffect(() => {
let shouldCancel = false;
handleCount(categoryId)
.then((data) => {
// A new category id was provided, or we unmounted. Do not call state changes
if (shouldCancel) return;
setSubcategoryCount(data.count); // Or however its structured
})
.catch((e) => {
// TODO: Log error, set error state for rendering
});
return () => {
shouldCancel = true;
};
}, [categoryId]);
// I believe you can just return a string without any elements around
// it but I wrapped it in a React Fragment just in case
return (
<>
`(${subcategoryCount})`
</>
);
}
然后你可以简单地:
<tbody>
{maincategorylist.map((maincat, index) => (
<tr key={maincat.id}>
<td>
{maincat.categoryName}
<SubcategoryCount categoryId={mainCat.id} />
</td>
</tr>
))}
</tbody>