【发布时间】:2020-03-10 17:39:07
【问题描述】:
我是一名自学成才的程序员/React 程序员,正在尝试使用 firebase firestore。
当我尝试这个时:
var docRef = db.collection("Marcus").doc("one")
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
this.setState({
test: doc.data()
});
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
完美运行。没有错误,文档在控制台中。
但是当我尝试将其添加到输入时
class LatestNews extends Component {
constructor(props) {
super(props)
this.state = {
test: "input"
}
}
componentDidMount() {
docRef.get().then(function(doc) {
if (doc.exists) {
this.setState({
test: doc.data()
});
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
}
componentDidUpdate() {
docRef.get().then(function(doc) {
if (doc.exists) {
this.setState({
test: doc.data()
}); } else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
}
render() {
return (
<div> <br/><br/>
<h1 className={Style.blue}>sup</h1>
<h1>{this.state.test}<News/> </h1>
它不起作用。如果我将其作为列表进行,则会针对集合中的文档数量显示项目符号,但不会出现任何文档。
我认为问题在于“state.test”部分或与不易转换为 HTML 的 firestore 格式有关。
控制台结果:
当传入控制台时: 文件数据: {Lnews:“这有效吗?”} Lnews:“这行得通吗?” 原型:对象
当尝试使用 get 中的内容设置状态时:
获取文档时出错:TypeError:无法读取未定义的属性“setState” 在 LatestNews.jsx:68
【问题讨论】:
-
两个答案都没有解决问题。
标签: javascript reactjs firebase google-cloud-firestore nosql