【问题标题】:how do i put the this data in the html?我如何将这些数据放在 html 中?
【发布时间】: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


【解决方案1】:

请使用 this.setState() 更新状态值

this.setState({
    test: doc.data()
});

【讨论】:

    【解决方案2】:

    你的代码 sn-p 的问题是,你直接改变了状态。如果您直接改变状态,则不会调用 render。

    修改很简单:

     this.state.test = doc.data();
    

    this.setState({
        test: doc.data()
    });
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      相关资源
      最近更新 更多