Javascript 如何将这些数据放入html中?
我是一名自学成才的程序员/react程序员,正在尝试firebase firestore 当我尝试这个:Javascript 如何将这些数据放入html中?,javascript,reactjs,firebase,google-cloud-firestore,nosql,Javascript,Reactjs,Firebase,Google Cloud Firestore,Nosql,我是一名自学成才的程序员/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: d
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>
类LatestNews扩展组件{
建造师(道具){
超级(道具)
此.state={
测试:“输入”
}
}
componentDidMount(){
docRef.get().then(函数(doc){
如果(文件存在){
这是我的国家({
测试:doc.data()
});
}否则{
//在这种情况下,将不定义doc.data()
log(“没有这样的文档!”);
}
}).catch(函数(错误){
log(“获取文档时出错:”,错误);
});
}
componentDidUpdate(){
docRef.get().then(函数(doc){
如果(文件存在){
这是我的国家({
测试:doc.data()
})其他的{
//在这种情况下,将不定义doc.data()
log(“没有这样的文档!”);
}
}).catch(函数(错误){
log(“获取文档时出错:”,错误);
});
}
render(){
返回(
啜饮
{this.state.test}
它不起作用。如果我把它作为一个列表来做,项目符号会显示集合中的文档数量,但不会显示任何文档
我认为问题在于“state.test”部分或者与firestore的格式有关的部分不容易转换为HTML
控制台结果:
当传递到控制台时:
文件数据:
{Lnews:“这有用吗?”}
Lnews:“这有用吗?”
原型:对象
尝试使用get中的内容设置状态时:
获取文档时出错:TypeError:无法读取未定义的属性“setState”
在LatestNews.jsx:68中,请使用此.setState()更新状态值
this.setState({
test: doc.data()
});
代码片段的问题是,您正在直接改变状态。如果您正在直接改变状态,则不会调用render 修复是简单的更改行:
this.state.test = doc.data();
到
两个答案都没有解决问题。
this.setState({
test: doc.data()
});