首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >转换为数组时无法获取firebase生成的ID

转换为数组时无法获取firebase生成的ID
EN

Stack Overflow用户
提问于 2020-05-29 12:55:28
回答 1查看 33关注 0票数 0

我使用CRA & axios从火基中提取一些JSON作为对象,然后将其转换为一个数组以供呈现。

这似乎是成功的,我可以记录数组,但是我似乎无法获取由firebase生成的ID (例如,-M9SUPLwY3KgRNmOLS17)。

这是我需要的,以便能够导航到正确的旅游页面。

预期结果:/旅游/-M9SUPLwY3KgRNmOLS 17/旅游

当前结果:/旅游/未确定/旅游

JSX

代码语言:javascript
复制
  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示例

代码语言:javascript
复制
{
 "-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
   }
 }
}

我肯定我错过了一些简单的东西,有什么建议吗?谢谢,

EN

回答 1

Stack Overflow用户

发布于 2020-05-29 17:06:37

文档的键是JavaScript对象键--否则它不会嵌入内容中。我想你可能想要这样的东西:

代码语言: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属性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62086546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档