reactjs - 在 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;
解决方案
跳出来给我的一件事是注释掉了console.log(joblist[0].datePosted)
,它最初会给出一个错误,因为数组仍然是空的。要抓住这一点,您需要执行以下操作:
if (joblist.length > 0) console.log(joblist[0].datePosted);
推荐阅读
- java - 如何更快地在 Java 中进行多线程处理?
- json - 将基于文本的键/值对转换为 JSON 格式
- flutter - Flutter - 从列表中返回属性设置为 true 的项目
- highcharts - 我们如何在单个高图中绘制带有堆积柱形图的柱形图?
- java - 发生了一些不寻常的事情导致驱动程序失败。Heroku postgresql 数据库
- python - 检测空列表的嵌套列表时如何返回True?
- swift - 如何从另一个视图控制器更改标签的文本并使用核心数据保存
- elasticsearch - 缺少 Geoshape 时的 Elasticsearch 版本 7.6 错误
- regex - 是否有任何免费的方式来搜索不受严格限制和简单的 github(又名:搜索特殊字符或使用正则表达式)?
- powerbi - PowerBi:在 DAX 公式中返回 id