【问题标题】:How to retrieve data from firebase in React? [closed]如何在 React 中从 firebase 检索数据? [关闭]
【发布时间】:2019-08-06 04:22:18
【问题描述】:

我正在使用 React 制作一个待办事项列表应用程序。 我能够将数据保存到 firebase 数据库中。但是,我不知道如何检索这些数据并将它们放入 JSX。我可以在控制台中打印它们。目前,我只通过在栏中输入并按回车来输出待办事项列表。

这是我的代码。有点乱。

   import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import firebase from 'firebase';

var config = {
    apiKey: "**********************",
    authDomain: "react-to-do-list-a8f6d.firebaseapp.com",
    databaseURL: "https://react-to-do-list-a8f6d.firebaseio.com",
    projectId: "react-to-do-list-a8f6d",
    storageBucket: "react-to-do-list-a8f6d.appspot.com",
    messagingSenderId: "673689778313"
};
firebase.initializeApp(config);

const database = firebase.database();
const ref = database.ref('todos');




// const todos = []
class Index extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            todo: '',
            todos: [],
            // database: 
        }
        this.handleInput = this.handleInput.bind(this)
        this.addTask = this.addTask.bind(this)
        this.check = this.check.bind(this)
    }
    handleInput(e) {
        this.setState({
            todo: e.target.value
        })
    }
    addTask(e) {
        if (e.keyCode === 13) {
            this.setState({
                todos: this.state.todos.concat(this.state.todo)
            })
            e.target.value = ''
            ref.push(this.state.todo)
        }
    }
    check(e) {
        if (e.target.style.textDecoration === "") {
            e.target.style.textDecoration = " line-through"
        } else {
            e.target.style.textDecoration = ""
        }
    }


    render() {

        ref.on('value', gotData, errData)

        function gotData(data) {
            let todos = data.val()
            // console.log(todos)
            let keys = Object.keys(todos)
            // console.log(keys)
            for (let i = 0; i < keys.length; i++) {
                let key = keys[i]
                let todo = todos[key]
                console.log(todo)
            }
        }

        function errData(err) {
            console.log('Error !')
            console.log(err)
        }

        return (
            <div className='container'>
                <h1>To Do List</h1>
                <input value={this.state.term} onKeyDown={this.addTask} onChange={this.handleInput} placeholder="  Add your tasks here"></input>
                <ul>
                    {this.state.todos.map(x => {
                        return (
                            <li>
                                <input type="checkbox" id={x} name={x} value={x} />
                                <label for={x}>{x}</label>
                            </li>
                        )
                    })}
                </ul>
            </div>
        )
    }
}
ReactDOM.render(<Index />, document.getElementById('root'));

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    由于 firebase 数据库是一个实时数据库,这意味着它可以为您提供数据所在位置的参考,并且可以在参考数据发生变化时触发您,这使您可以捕获给定参考数据的快照。

    使用firebase.database().ref().on('value') 方法在引用处获取数据几乎是正确的。

    您可以进一步添加这样的回调:

    firebase
          .database()
          .ref(
            firebase_basepath + `${tenantId}/${userId}/task/product/${referenceId}`
          )
          .on("value", snapshot => {
            console.log("FireB ",snapshot)
            if (snapshot && snapshot.exists()) {
               //Set values in state which can be extracted in jsx in render. 
            }})
    

    现在随着状态的改变,函数将重新渲染,并且可以在 jsx 中设置值。

    【讨论】:

    • 您也可以将其提取到componentDidMount中,您只需在渲染时触发一次,将其保留在渲染中将在每次UI中的某些内容强制渲染时继续触发。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    相关资源
    最近更新 更多