gpt4 book ai didi

javascript - 如何使用 React 从 Promise 函数将带有键的数组输出到我的 html 文件

转载 作者:行者123 更新时间:2023-11-28 14:24:30 24 4
gpt4 key购买 nike

我有一些带有标签“bookName”和“author”的 Firebase 数据库。如何从函数“getBook”渲染数组?

import React, {Component} from 'react';
import firebase from '../firebase/firebase.js';

export default class booksComponent extends Component{

getBook(){
const newArray = [];
console.log("i am working")
const db = firebase.firestore();
db.settings({
timestampsInSnapshots: true
});
db.collection("LibraryDB").where("user", "==",
firebase.auth().currentUser.uid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
newArray.push(doc.data());
});
return(newArray);
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
};
render(){
return(
<div>
<button/>
<div>
------
{this.getBook()}
</div>
</div>
)};
};

在控制台输出看起来像:

[{author: "Ernest Hemingway", bookName: "Fiesta", user: 
"eZGZbRijz6RF8FkMhngiE9FAnf63"},
{author: "J. R. R. Tolkien", bookName: "LOTR", user:
"eZGZbRijz6RF8FkMhngiE9FAnf63"},
{author: "Ernest Hemingway", bookName: "The Old Man and Sea", user:
"eZGZbRijz6RF8FkMhngiE9FAnf63"}]

但是如何将这些信息传递给render()呢?

最佳答案

试试这个

import React, {Component} from 'react';
import firebase from '../firebase/firebase.js';

export default class BooksComponent extends Component{
constructor(props) {
super(props)
this.state = {
books: []
}
this.getBook = this.getBook.bind(this);
}
componentDidMount() {
this.getBook();
}
getBook(){
const newArray = [];
const selfThis = this;
console.log("i am working")
const db = firebase.firestore();
db.settings({
timestampsInSnapshots: true
});
db.collection("LibraryDB").where("user", "==",
firebase.auth().currentUser.uid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
newArray.push(doc.data());
});
selfThis.setState({
books: newArray
})
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
};
render(){

return(
<div>

<div>
<button onClick={this.getBook}/>
<div>
------
<table>
<tr>
<th>Author</th>
<th>Book Name</th>
</tr>
{this.state.books.map(book => <tr key={book.user}>
<td>{book.author}</td>
<td>{book.bookName}</td>
</tr>)}
</table>
</div>

)};
};

关于javascript - 如何使用 React 从 Promise 函数将带有键的数组输出到我的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54013402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com