【问题标题】:How to query in firebase database in react?如何在firebase数据库中查询反应?
【发布时间】:2018-07-23 03:02:58
【问题描述】:

我在 firebase 中有以下数据结构作为实时数据库:

{
  "react" : {
    "url_01" : "https://stackoverflow.com/",
    "url_02" : "https://google.com/",
    "url_03" : "https://www.youtube.com/"
  }
}

我正在尝试在 React 中查询数据库以显示以下组件中的所有 URL。

到目前为止,我可以正确显示数据库中的第一个 URL,但现在尝试在 div 中将它们全部显示为<h1>

class FirebaseDB extends React.Component {
  constructor() {
    super();
    this.state = {
      speed: [],
    };
  }

  componentDidMount() {
    const rootRef = firebase.database().ref().child('react');
    const speedRef = rootRef.child('url_01');
    speedRef.on('value', snap => {
      this.setState({
        speed: snap.val()
      });
    });
  }

  render() {
    return (

        <div>
          <h1>URL: {this.state.speed}</h1>
        </div>


    );
  }
}

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:
    componentDidMount() {
        const rootRef = firebase.database().ref();
        const speedRef = rootRef.child('react');
    
        speedRef.once("value", snap => {
            // Handle state
            let speedsUrls = []
            snap.forEach(child => {
                speedsUrls.push(child.val())
            });
            this.setState({speed: speedsUrls})
        });
    }
    
    render() {
        const SpeedURLS = this.state.speed.map(url => <h1>URL: {url}</h1>);
        return (
            <div>
                {SpeedURLS}
            </div>
        );
    }
    

    【讨论】:

    • 无论如何要让结果在 div 中显示为 h1 类?将其呈现到页面时遇到问题。
    • 看新版,只需要使用url数组进行render()
    【解决方案2】:

    另一种解决方案:

    const object1 = {
        "url_01" : "https://stackoverflow.com/",
        "url_02" : "https://google.com/",
        "url_03" : "https://www.youtube.com/"
    };
    
    let a = Object.values(object1);
    

    现在是

    ["https://stackoverflow.com/","https://google.com/","https://www.youtube.com/"]
    

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多