如何遍历Firebase中的对象数组?

时间:2018-08-03 13:21:17

标签: javascript reactjs firebase

我试图遍历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);

1 个答案:

答案 0 :(得分:0)

不知道如何初始化this.props.champ.stats很难确定,但是我猜这是从Firebase数据库获得的DataSnapshot

尽管DataSnapshot一眼看上去就像一个数组,但它没有实现Array.map()。它确实但是实现了forEach(),因此您可以使用 that 遍历项目,然后将每个项目分别呈现为HTML。