我有一个名为company
的数组,它在mongo DB中保存了多个名为details
的对象,我需要从中获取数据,特别是,我想从company array
中获取company name
和employee's names
,并将它们显示在list
中。我的问题是如何在数组中进行钻取并呈现company
和employee names
。
当前在List component
中的嵌套映射中,当我执行details.employee
时,我只能从company ABC
获得person1
的结果,并且我需要从company ABC
和company EFG
中显示的所有结果person 1, 2, and 3
";
以下是来自sandbox的代码(请注意,只需查看List.js(
import axios from "axios";
import { useEffect, useState } from "react";
const List = () => {
const [company, setCompany] = useState([
{
details: [
{
employee: "person2",
date: "test date",
tax: "test tax",
balance: "22"
},
{
employee: "person3",
date: "test date",
tax: "test tax",
balance: "22"
}
],
company: "TEST-ABC",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
},
{
details: {
employee: "person1",
date: "test date",
tax: "test tax",
balance: "22"
},
company: "TEST-EFG",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
}
]);
return (
<>
<h2>Customer List</h2>
{company.map((c, i) => (
<ul key={i}>
{c.company}
{company.map((d, i) => (
<li key={i}>{d.details.employee}</li>
))}
</ul>
))}
</>
);
};
export default List;
return (
<>
<h2>Customer List</h2>
{company.map((c, i) => (
<li key={i}>
{c.company}
{company.map((d, i) => (
<li key={i}>{d.details.employee}</li>
))}
</li>
))}
</>
);
};
export default List;
内部循环需要覆盖员工,而不是再次覆盖company
。
考虑将有状态变量设为复数,这样也更容易理解。(由于在映射时需要引用单个公司,因此不希望整个公司阵列也被命名为company
(
输入结构很奇怪,detail
看起来要么是数组,要么是对象。(如果可能的话,请将结构更改为一致,使其始终为数组。否则,每次渲染时都必须检查它是数组还是对象。(
现场演示:
const App = () => {
const [companies, setCompanies] = React.useState([
{
details: [
{
employee: "person2",
date: "test date",
tax: "test tax",
balance: "22"
},
{
employee: "person3",
date: "test date",
tax: "test tax",
balance: "22"
}
],
company: "TEST-ABC",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
},
{
details: {
employee: "person1",
date: "test date",
tax: "test tax",
balance: "22"
},
company: "TEST-EFG",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
}
]);
return (
<React.Fragment>
<h2>Customer List</h2>
{companies.map((company, i) => (
<ul key={i}>
{company.company}
{
Array.isArray(company.details)
? company.details.map((detail, j) => <li key={j}>{detail.employee}</li>)
: company.details.employee
}
</ul>
))}
</React.Fragment>
);
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>