首页 > 解决方案 > 在 react.js 中访问实时 firebase 对象

问题描述

当前尝试访问我们的 Joblist 对象中的值。我们无法执行应返回 google 的 joblist[0].company。

访问对象值的最佳方式是什么?

我们的 joblist 对象包含:
key: value
company: "Google"
datePosted: "2021-09-20T05:00:00.000Z"
location: "San Francisco"
position: "SWE Intern"

[{ 
  "company" : "Google", 
  "datePosted" : "2021-09-20T05:00:00.000Z", 
  "id" : 0, 
  "location" : 
  "San Francisco", 
  "position" : "SWE Intern" 
}]

App.js 代码:

class App extends React.Component {
  
  constructor(props) {
      
      super(props);
    
      this.state = {joblist : []}
    }
      
    componentDidMount() {
      firebase.database().ref("1h5GOL1WIfNEOtcxJVFQ0x_bgJxsPN5zJgVJOePmgJOY/Jobs").on("value", snapshot => {
        let jobs = [];
        snapshot.forEach(snap => {
            // snap.val() is the dictionary with all your keys/values from the 'students-list' path
            jobs.push(snap.val());
        });
        this.setState({ joblist: jobs });
      });

    }
    render(){
    const {joblist} = this.state;
    // console.log(joblist[0].datePosted)
    console.log(joblist);

    return ( 
      <div id='body'>
        

        <Header />
        <PhoneInput />
        <TableHeader />
        <Table joblist = {joblist}/>
        <Footer />
      </div>
      
    );
  }
  }
  export default App;

标签: reactjsfirebasefirebase-realtime-database

解决方案


跳出来给我的一件事是注释掉了console.log(joblist[0].datePosted),它最初会给出一个错误,因为数组仍然是空的。要抓住这一点,您需要执行以下操作:

if (joblist.length > 0) console.log(joblist[0].datePosted);

推荐阅读