【发布时间】:2019-12-31 08:55:57
【问题描述】:
所以我尝试按照here
的教程将我的帖子详细信息映射到卡片它给出了“TypeError: Cannot read property 'map' of undefined”
我搜索了 stackoverflow 和其他网站,但没有一个帮助我解决这个问题。
编译器也给了我这个警告。
./src/components/dummy-posts.js
第 1:7 行:“posts”被分配了一个值,但从未使用过 no-unused-vars
这是我的代码:
App.js
import React, { Component } from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar'
import TypoGraphy from '@material-ui/core/Typography'
import NavBar from './components/nav'
import Posts from './components/posts'
class App extends Component {
render() {
return (
<div>
<div>
<AppBar color="primary" position="static">
<Toolbar>
<TypoGraphy variant="title" color="inherit">
My header
</TypoGraphy>
<NavBar />
</Toolbar>
</AppBar>
</div>
<Posts/> {/*This is the function which gets the posts component*}
</div>
);
}
}
export default App;
posts.js
import React from "react";
import { Grid,Typography } from "@material-ui/core";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Button from "@material-ui/core/Button";
import { posts } from "./dummy-posts";
function Posts(props) {
return (
<div style={{ marginTop: 20, padding: 30 }}>
<Grid container spacing={40} justify="center">
{posts.map(post => ( {/*Here's where the error occurs*/}
<Grid item key={post.title}>
<Card>
<CardActionArea>
<CardMedia
component="img"
alt="Contemplative Reptile"
height="140"
image={post.image}
title="Contemplative Reptile"
/>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{post.title}
</Typography>
<Typography component="p">{post.excerpt}</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button size="small" color="primary">
Share
</Button>
<Button size="small" color="primary">
Learn More
</Button>
</CardActions>
</Card>
</Grid>
))}
</Grid>
</div>
);
}
export default Posts;
dummy-posts.js
const posts=[
{
title: "My first post",
excerpt: "This is my first post with more content inside",
image: "random_url"
},
{
title: "My second post",
excerpt: "This is my second post with more content inside",
image: "random_url"
},
{
title: "My third post",
excerpt: "This is my third post with more content inside",
image: "random_url"
},
{
title: "My fourth post",
excerpt: "This is my fourth post with more content inside",
image: "random_url"
},
{
title: "My fifth post",
excerpt: "This is my fifth post with more content inside",
image: "random_url"
},
{
title: "My sixth post",
excerpt: "This is my sixth post with more content inside",
image: "random_url"
}
]
请帮助我。在此先感谢。
【问题讨论】:
-
在你的 dummy-posts.js 中你导出了帖子数组吗?
-
您的
posts值未定义。您是否正确导出它,如果是,您可以共享它的代码。也请 console.log 你的帖子进行检查。 -
谢谢,我不知道我们甚至必须导出常量才能从其他文件中导入它们。它成功了!
标签: javascript reactjs material-ui