i'm having a little trouble with a for loop. This program gathers data from my back end, and is supposed to loop through the data. But, the loop is only displaying 1 _id, and console.logging two 10's. I appreciate the help in advanced, and all tips / criticism is appreciated.
**The problem seems to be in the i++... if i log I every time, it stays as 0!
import React, { Component } from 'react';
import getTransactions from '../api/TransactionAPI';
export class Dashboard extends Component {
state = {
transactions: ""
}
componentDidMount() {
getTransactions().then(res => {
this.setState({ transactions: res.data });
}).catch(error => {
console.log(error)
});
}
mapData(data) {
for (let i = 0; i < data.length; i++) {
console.log(data.length);
return <h1>{data[i]._id}</h1>
}
}
render() {
if (this.state.transactions === "") {
return (
<p>loading...</p>
)
} else {
return (
<div>
{ this.mapData(this.state.transactions) }
</div>
)
}
}
}
export default Dashboard;
You aren't returning anything from mapData
. Try
mapData(data) {
const elements = [];
for (let i = 0; i < data.length; i++) {
console.log(data.length);
elements.push(<h1>{data[i]._id}</h1>)
}
return elements;
}
Additionally, instead of a for loop, (making some assumptions about your data
) you can use .map
instead.
mapData(data) {
return data.map(d => (
<h1>{d._id}</hi>
))
}
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.