【发布时间】:2019-09-17 19:29:03
【问题描述】:
我在运行我的应用程序时收到以下错误消息。
TypeError: Cannot read property 'map' of undefined
我将 Grid.js 导入到我的 Index.js 文件中,如下所示。我希望 Grid.js 显示在 Index.js 页面上,但是我收到 TypeError: Cannot read property 'map' of undefined error。
Grid.js
import React, { Component } from 'react';
import axios from 'axios';
class Grid extends React.Component {
state = {
posts: [],
isLoading: true,
errors: null
};
getPosts() {
axios
.get("http://localhost:1337/posts")
.then(response => {
this.setState({
posts: response.data.posts,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
componentDidMount() {
this.getPosts();
}
render(){
const { isLoading, posts } = this.state;
return <div>
<div className="row">
{!isLoading ? (
posts.map(post => {
const { _id, title, content } = post;
return (
<div className="col-lg-2 col-md-3 col-sm-6 col-6" key={_id}>
<div className="list-item slick-item r list-hover mb-3">
<div className="media text-hover-primary">
<span className=" media-content"><i className="fas fa-images fa-4x text-muted"></i></span>
<div className="media-action media-action-overlay">
<div className="row">
<div className="w-100 text-center mt-2 h-1x">
Misc Meta Properties
</div>
<div className="w-100 text-center mt-4">
<a className="btn btn-sm btn-outline-light btn-rounded mx-3" href="{item.url}">View Type</a>
</div>
</div>
</div>
</div>
<div className="list-content text-center">
<div className="list-body">
<a className="list-title title" href="{item.url}">{title}</a>
<a className="list-subtitle d-block text-muted subtitle text-small ajax" href="{item.url}">Brand</a>
</div>
</div>
</div>
</div> );
})
) : (
<p>
</p>
)}
</div></div>
}
}
export default Grid;
Index.js(页面/index.js)
import Header from '../components/Header'
import Grid from '../components/Grid'
import Welcome from '../components/Welcome'
import Footer from '../components/Footer'
import "../style.css"
const Index = () => (
<div>
<body className="bg-dark">
<Header></Header>
<Welcome></Welcome>
<div className="container">
<Grid/>
<Footer/>
</div>
</body>
</div>
)
export default Index
使用 NextJs 的 getInitialProps 函数时,我能够成功读取和显示数据。但是,我希望这个 API 放在一个我可以调用的漂亮组件文件中,而不是把它全部放在 Index.js 页面上,然后用 this.props.title 等对其进行迭代。
有什么想法吗?
编辑:
从控制台: [{"id":1,"title":"test","content":"test","created_at":1556521391304,"updated_at":1556521391312},{"id":2,"title":"test ","content":"test","created_at":1556521394698,"updated_at":1556521394702}]
直接从 API (Strapi) 浏览到 http://localhost:1337/posts/ 时 [{"id":1,"title":"test","content":"test","created_at":1556521391304,"updated_at":1556521391312},{"id":2,"title":"test ","content":"test","created_at":1556521394698,"updated_at":1556521394702}]
【问题讨论】:
-
你能记录
response.data.posts的值吗? -
确保您在 response.data.posts 中获取值数组
-
是的,它显示在 console.log 中
-
试试条件
posts && posts.map -
@MattCohen,你能在你的帖子中发布日志值吗?