[英]Get data of a field from a collection using a selected document in Firestore and React
I am looking to display the data in a field.我希望在字段中显示数据。 At this time, my database structure is represented in Firestore like the following: Collection (lunch) => document (mon, tue, web, thu, fri) => field (dessert, main, side, soup)
此时,我的数据库结构在 Firestore 中表示如下: Collection (lunch) => document (mon, tue, web, thu, fri) => field (dessert, main, side, soup)
Firestore database structure Firestore 数据库结构
What I am trying to do here is get all the documents from the collection and retrieve it by mapping.我在这里要做的是从集合中获取所有文档并通过映射检索它。 The expected result is to return one value in a selected field.
预期结果是在选定字段中返回一个值。 For example, I want to display dessert of tue.
例如,我想显示周二的甜点。 The result should display "Banana & Coconut Tapioca Pudding".
结果应显示“香蕉和椰子木薯布丁”。 However, it returned to all the data locating on the field.
但是,它返回了位于该字段上的所有数据。 Like the illustrating image below.
如下图所示。
Here is the code snippet I tried using but it did not work:这是我尝试使用但不起作用的代码片段:
export default function Menu() {
const [menu, setMenu] = useState([]);
useEffect(() => {
fetchMenu();
}, []);
useEffect(() => {
console.log(menu)
}, [menu]);
function fetchMenu() {
const menuCollection = collection(db, 'lunch')
getDocs(menuCollection)
// .then((doc)=>{console.log(doc.data(),doc.id)})
.then(response => {
const menuRef = response.docs.map((doc) =>(
{
data:doc.data(),
id: doc.id
}
))
setMenu(menuRef)
})
.catch(error => console.log(error.message))
}
return (
<>
<SubNav content="Menu"></SubNav>
<div className="App">
<ul>
{menu.map((menu) => (
<li key={menu.tue}>{menu.data.dessert}</li>
))}
</ul>
</div>
</>
);
Thank you!谢谢!
As per your image you your menu looks like根据您的图像,您的菜单看起来像
[
{data: {...}, id: 'mon'},
{data: {...}, id: 'tue'},
{data: {...}, id: 'wed'},
]
So while iterating on this array menu.tue won't work you would have to do a if check like this因此,在迭代此数组 menu.tue 时,您将不得不像这样进行 if 检查
<ul>
{menu.map((menu) => (menu.id === 'tue' &&
<li key={menu.tue}>{menu.data.dessert}</li>
))}
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.