我使用CRA & axios从火基中提取一些JSON作为对象,然后将其转换为一个数组以供呈现。
这似乎是成功的,我可以记录数组,但是我似乎无法获取由firebase生成的ID (例如,-M9SUPLwY3KgRNmOLS17)。
这是我需要的,以便能够导航到正确的旅游页面。
预期结果:/旅游/-M9SUPLwY3KgRNmOLS 17/旅游
当前结果:/旅游/未确定/旅游
JSX
componentDidMount() {
axios.get('FIREBASEURL/tours.json')
.then(response => {
const obj = response.data;
const resArr = []
for (let key in obj) {
resArr.push(obj[key])
}
this.tours = resArr
this.setState({tours: resArr})
})
}
render() {
const { tours } = this.state
return (
<div>
<div className="tours">
{tours ? (tours.map(tours => (
<Link to={`/tours/${tours.id}/tour`} className="trslink">
<div key={tours.id + Math.random()} className="trsIndiv">
<h3 className="title">{tours.tour.name}</h3>
<div className="desc">{tours.tour.description}</div>
<p className="longdesc">
<strong>City:</strong> {tours.tour.city}<br/>
<strong>Duration:</strong> {tours.tour.duration} hrs<br/><br/>
</p>
</div>
</Link>
))
) : (
<div></div>
)}
</div>
</div>
)
}JSON示例
{
"-GHJSDAGFAD1" : {
"tour" : {
"city" : "London, England",
"description" : "Drink to your hearts content.",
"duration" : 5,
"full_description" : "Long Description TBC",
"name" : "The Fighting Lion",
"rating" : 4
}
},
"-QEWURYK2" : {
"tour" : {
"city" : "London, England",
"description" : "Top Pub!",
"duration" : 2,
"full_description" : "Long Description TBC",
"name" : "The Frisky Goose",
"rating" : 3.5
}
}
}我肯定我错过了一些简单的东西,有什么建议吗?谢谢,
发布于 2020-05-29 17:06:37
文档的键是JavaScript对象键--否则它不会嵌入内容中。我想你可能想要这样的东西:
axios.get('FIREBASEURL/tours.json')
.then(response => {
const obj = response.data;
const resArr = []
for (let key in obj) {
resArr.push(Object.assign({id: key}, obj[key]))
}
this.tours = resArr
this.setState({tours: resArr})
})区别在于Object.assign向数组中的结果对象添加了一个id属性。
https://stackoverflow.com/questions/62086546
复制相似问题