好的,所以每个人都知道单独的映射可以在 React 渲染方法中渲染组件,如下所示:
var listOfService = ['A', 'B', 'C', 'D', 'E'];
const listItems = listOfService.map((singleItem) =>
<a className="style_class">{singleItem}</a>
);
如果您调用
listItems
在渲染方法的返回中,您将获得列表和单个列表的列表,但我有一个 firebase firestore 数据库,我想遍历该数据库并将每个文档打印为我称为服务的 React 组件,我知道你不能在循环或 if 语句中使用 JSX 所以我试过这个:renderServices() {
let db = firebase.firestore();
var details = [[]];
db.collection('providers').get().then(function (snapshot) {
snapshot.forEach(function (doc) {
details.push(
[
doc.data().owner_name,
doc.data().experience,
doc.data().charges,
doc.data().address,
doc.data().home_service,
doc.data().highlights,
doc.data().certifications,
doc.data().specialty,
doc.data().facility
]
);
//tried loading here Serivce, didn't work
});
})
.catch(function (error) {
console.log(error);
});
details.map((singleDetail) =>
(< Service details={singleDetail} />)
);
}
所以我尝试了这个但它不起作用,我写了一些控制台日志并且数据正确输入。首先,我获得了整个“
providers
”文档数组,该提供者列表作为“snapshot
”传递,因此我使用另一个函数遍历快照,该函数正在获取一个名为 doc
的单个文档。然后将其插入 var
叫 details
,这是一个数组数组但是!它不起作用,即使数据在那里也没有填充数组,因此我无法映射,关于如何处理这个问题的任何想法?
最佳答案
您需要将数据加载和渲染分开,因为检索数据是 asynchronous
和渲染需要synchronous
.
例如,在您的情况下,您将详细信息推送到 then
中的数组中。回调 - 这会发生 async
到您的主要功能,因此当您调用 details.map
时它仍然是空的(没有触发回调来填充它)。
相反,您可以加载数据并将其存储在状态中,然后在可用时呈现它。我个人更喜欢async/await
但是使用 then
可以实现相同的逻辑关于 promise :
const [details, setDetails] = useState([]);
// Load the data on initial load or setup the effect to fire when reload is needed
useEffect(() => {
// Async function that loads the data and sets the state once ready
const loadData = async () => {
const details = [];
try {
const snapshot = await db.collection('providers').get();
snapshot.forEach((doc) => {
details.push([
// your details stuff
]);
}
} catch (ex) {
// Handle any loading exceptions
}
setDetails(details);
}
}, [])
// Render the available details, you could also add conditional rendering to check
// if the details are available or not yet
return (
<div>
{details.map((singleDetail) => (
<Service details={singleDetail} />
)};
</div>
);
如果你使用的是 React 类而不是函数式组件,你可以从
componentDidMount
调用加载并在加载后仍然设置状态,然后在渲染时映射状态数据。
关于javascript - 在 ReactJS 中使用单独的方法填充渲染方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60173053/