【问题标题】:Create a React component for each element on JSON为 JSON 上的每个元素创建一个 React 组件
【发布时间】:2018-12-28 23:52:49
【问题描述】:

我需要为 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 数据结构

【问题讨论】:

  • 你能提供一个数据/数据结构的例子吗?
  • 这似乎是一个异步问题。 bookComponentthen 函数中分配之前返回。可以通过使用 async/await (javascript.info/async-await) 而不是回调来解决。
  • 我不认为渲染函数可以是aysnc。这就是为什么所有 React 文档都建议在 componentDidMount 中加载数据,然后在成功时更新状态以导致重新渲染。

标签: javascript json reactjs firebase


【解决方案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} .../>
    });
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2023-03-06
    • 1970-01-01
    • 2021-12-08
    • 2019-01-07
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多