English is not my native language, but I will try to make myself understand my best.
In the axios_cards component I am doing a get by axios to an api json and I assign to another component the list of objects as property
import React, { Component } from 'react';
import axios from 'axios';
import CardsGrid from "../Pages/CardsGrid"
class Axios_cards extends Component {
constructor(props) {
super(props)
this.state = {
courses : []
}
}
componentDidMount() {
axios.get('http://my-json-server.typicode.com/jee4nc/myjsonserver/lista')
.then(response => this.setState({
courses: response.data
}))
}
render() {
const {courses} = this.state
return <CardsGrid courses={courses}/>
}
}
export default Axios_cards;
But in the component to which I assign the properties, it does not recognize the array and does not allow me to map the list
import React from 'react';
import Cards from "../Molecules/Cards"
const CardsGrid = ({courses}) => (
<div className="ed-grid m-grid-3">
{
courses.map( e =>
<Cards
id={e.id}
title={e.title}
description={e.description}
image={e.image}
price={e.price}
key={e.id}
/>)
}
</div>
)
export default CardsGrid;
does not recognize courses to be able to map
TypeError: Cannot read property 'map' of undefined
CardsGrid
src/Components/Pages/CardsGrid.jsx:5
2 | import Cards from "../Molecules/Cards"
3 |
4 | const CardsGrid = ({courses}) => (
> 5 | <div className="ed-grid m-grid-3">
6 | {
7 | courses.map( e =>
8 | <Cards
What if your response.data is null or not an array?
This should resolve it
<div className="ed-grid m-grid-3">
{
Array.isArray(courses)? courses.map( e =>
<Cards
id={e.id}
title={e.title}
description={e.description}
image={e.image}
price={e.price}
key={e.id}
/>) : null
}
</div>
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.