【问题标题】:How to loop through array of objects in Firebase?如何遍历 Firebase 中的对象数组?
【发布时间】:2018-08-03 13:21:17
【问题描述】:

我正在尝试遍历 Firebase 中的一组对象,在我的情况下,我正在尝试访问统计数据中的数据,但我不确定如何访问该值,我正在尝试使用地图,但它给了我一个错误说:

无法读取未定义的属性映射

代码:

// Champs
// -LIvNqyUt8Bsvrspears
// id:
// "-LIvNqyUt8Bsvrspears"
// img:
// "https://vignette.wikia.nocookie.net/leagueofleg..."
// img2:
// "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB..."
// name:
// "Ronaldo"
//     Stats
//        lvl: "medium"
//        "win rate ": "51%"

// Team: "real madrid"

import React, { Component } from "react";
import { ChampsRef, timeRef } from "./reference";
import { getsinglechamp } from "../actions/champs";
import { connect } from "react-redux"; // this is not being used.  oh isee so like this?
import { Redirect, Link } from "react-router-dom";
class OneChamp extends Component {
  state = {
    name: "",
    weak: [],
    img: ""
  };

  componentWillMount() {
    const { dispatch, match } = this.props;
    dispatch(getsinglechamp(match.params.id));
    console.log(this.props);
  }

  render() {
    console.log(this.props.champ);
    const { dispatch, loading } = this.props;
    console.log("change", this.props);
    console.log(this.props.champ.stats);
    let content = null;
    if (loading) {
      content = <p>Loading...</p>;
    } else {
      content = (
        <div>
          <div>
            <h1>{this.props.champ.name}</h1>
            <img src={this.props.champ.img} height="80px" />
          </div>

          <br />

          <ul>
            {this.props.champ.stats.map(stats => (
              <div>
                <li>{stats.lvl} </li>
              </div>
            ))}
          </ul>
        </div>
      );
    }

    return <div>{content}</div>;
  }
}

const mapStateToProps = state => {
  console.log("champs", state.champs);
  console.log(state.loading);
  return {
    champ: state.champs.champ,
    loading: state.loading
  };
};

export default connect(
  mapStateToProps,
  null
)(OneChamp);

【问题讨论】:

  • 这样做console.log(this.props.champ.stats);会得到什么。你得到一个数组或对象吗?
  • 是的,我得到了一个对象
  • 说map不是函数
  • 试试这个Object.keys(this.props.champ.stats).map(stats =&gt;.....
  • 是的,谢谢!

标签: javascript reactjs firebase


【解决方案1】:

如果没有看到您如何初始化 this.props.champ.stats,很难确定,但我猜这是您从 Firebase 数据库获得的 DataSnapshot

虽然DataSnapshot 乍一看可能看起来像一个数组,但它并没有实现Array.map()。但它确实实现了forEach(),因此您可以使用 that 循环遍历项目,然后将每个项目单独呈现为 HTML。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2020-12-03
    • 2021-02-25
    • 2015-10-17
    • 1970-01-01
    相关资源
    最近更新 更多