为JSON上的每个元素创建一个React组件

时间:2018-12-28 23:52:49

标签: javascript json reactjs firebase

我需要咨询如何为JSON中的每个元素渲染React组件(在本例中为Firebase数据库)。 我正在尝试创建书籍数据数组并将其推送到 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数据结构

enter image description here

1 个答案:

答案 0 :(得分:1)

.then的执行是异步的。因此,您实际上在返回bookComponent之前甚至还没有填充它。在React开发操作中,此类从FireBase检索数据在生命周期挂钩中执行以填充状态,然后呈现状态。您可以使用类组件轻松完成此操作:

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} .../>
    });
  }
}