I'm trying to loop through an array of objects inside of Firebase, in my case I'm trying to access the data in stats, and I'm not sure how to access that value, I'm trying to use map but its giving me an error saying:
cannot read property map of undefined
Code:
// 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);
It's hard to be certain without seeing how you initialize this.props.champ.stats
, but my guess is that this is a DataSnapshot
you get from the Firebase Database.
While a DataSnapshot
may look like an array at a glance, it does not implement Array.map()
. It does however implement forEach()
so you could use that to loop over the items, and then render each individually to HTML.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.