我需要咨询为 JSON 中的每个元素(在本例中为 Firebase 数据库)呈现 React 组件。 我正在尝试创建一个书籍数据数组并将其推送到一个数组 bookKeysArray,然后我将使用它进行映射。
结果我收到错误消息,组件 ListOfUserBooks 未返回任何内容(bookComponent 未定义)。
有人有什么建议吗?
function ListOfUserBooks(props) {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
let bookKeysArray = [],
bookComponent;
userBooksDataRef.once('value')
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...
let bookDataArray = [description, ...];
bookKeysArray.push(bookDataArray);
bookComponent = bookKeysArray.map((book, index) => {
<ListOfUserBooks_ListView key = {index}
description = {book.description}
.../>
});
}
});
});
return bookComponent;
};
Firebase 数据结构
最佳答案
.then
的执行是异步的。所以你实际上是在填充 bookComponent
之前返回它。在 React 开发中,诸如从 FireBase 检索数据的操作在生命周期 Hook 中执行以填充状态然后呈现它。您可以使用类组件轻松完成此操作:
class ListOfUserBooks extends React.Component {
constructor(...args) {
super(...args)
this.state = { bookKeysArray: [] }
}
componentDidMount() {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
userBooksDataRef.once('value')
.then((snapshot) => {
bookKeysArray = []
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...
bookKeysArray.push([description, ...]);
})
this.setState({ bookKeysArray })
}
render() {
return this.state.bookKeysArray.map((book, index) => {
return <ListOfUserBooks_ListView key = {index} .../>
});
}
}
关于javascript - 为 JSON 上的每个元素创建一个 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53965525/