如何从 firebase 获得正常响应。我尝试过这样的事情:
const db = ref(getDatabase(),'Restaurants/');
let data = []
onValue(db, (snapshot) => {
data = snapshot.val();
return data
});
console.log(data)
然后我将它放入一个新数组中:
let list = []
for( let i =0;i<=data.length;i++){
if (data[i] === undefined){
continue
}
else{
console.log(data[i])
list.push(data[i])
}
}
我正在尝试像这样显示 html 标记:
return(
<div className="restaraunts">
{list.map((restaraunt) => (
<div className="restaraunt-info">
<span className="restaraunt-name"> {restaraunt.name}</span>
<span className="restaraunt-desc"> {restaraunt.name}</span>
<span className="restaraunt-price">{restaraunt.name}</span>
<span className="restaraunt-time">{restaraunt.name}</span>
<span className="restaraunt-logo"> {restaraunt.name}</span>
</div>
))}
</div>
)
完整代码:
import React from 'react';
import {useState} from 'react'
import { getDatabase, ref, child, get,onValue } from "firebase/database";
function Restaraunts(){
const db = ref(getDatabase(),'Restaurants/');
let data = []
onValue(db, (snapshot) => {
data = snapshot.val();
return data
});
console.log(data)
let list = []
for( let i =0;i<=data.length;i++){
if (data[i] === undefined){
continue
}
else{
console.log(data[i])
list.push(data[i])
}
}
console.log(list)
return(
<div className="restaraunts">
{list.map((restaraunt) => (
<div className="restaraunt-info">
<span className="restaraunt-name"> {restaraunt.name}</span>
<span className="restaraunt-desc"> {restaraunt.name}</span>
<span className="restaraunt-price">{restaraunt.name}</span>
<span className="restaraunt-time">{restaraunt.name}</span>
<span className="restaraunt-logo"> {restaraunt.name}</span>
</div>
))}
</div>
)
}
export default Restaraunts
我刚开始使用 react 和 firebase。主要问题是为什么我得到一个空数组?以及如何以 HTML 格式输出所有接收到的数据。

对 firebase 的请求是异步的,建议在 hook 中完成
useEffect。有关您的特定组件,请参阅下面的评论。另请参阅官方文档中的示例。