反应错误:无法读取未定义的属性“地图”

时间:2020-06-21 03:29:29

标签: reactjs

我一直在尝试解决此错误近2个小时,但没有运气。我什至研究并使用了bind方法,但是映射通过父组件传递的prop仍然没有运气。非常感谢您的帮助。

import React from "react";
import { Link } from "react-router-dom";

const PostList = ({ postItem }) => {
    postItem.map((post) => (
        <div className="mx-auto mb-3 card w-75" key={post.id}>
            <div className="card-body">
                <h5 className="card-title">{post.title}</h5>
                <p className="card-text">{post.comment}</p>
                <Link to="/create">
                    <ion-icon
                        style={{ color: "#fc5185", fontSize: "20px" }}
                        name="trash-outline"
                    ></ion-icon>
                </Link>
            </div>
        </div>
    ));
};

export default PostList;

父组件是

class Dashboard extends Component {
    state = {
        posts: [
            {
                id: 1,
                title: "Hello",
                comment: "it is sunny today",
            },
        ],
    };

    createPost = (title, comment) => {
        const newPost = {
            id: Math.floor(Math.random() * 1000),
            title,
            comment,
        };
        this.setState({
            posts: [...this.state.posts, newPost],
        });
    };
    render() {
        return (
            <div>
                <CreatePost createPost={this.createPost} />
                <PostList postItem={this.state.posts} />
            </div>
        );
    }
}

export default Dashboard;

1 个答案:

答案 0 :(得分:0)

我想您错过了向PostList组件添加收益的方法,您可以通过三种方式(请参阅arrow functions

const PostList = ({ postItem }) => postItem.map((post) => (
    <div className="mx-auto mb-3 card w-75" key={post.id}>
        <div className="card-body">
            <h5 className="card-title">{post.title}</h5>
            <p className="card-text">{post.comment}</p>
        </div>
    </div>
));

const PostList = ({ postItem }) => (
    postItem.map((post) => (
        <div className="mx-auto mb-3 card w-75" key={post.id}>
            <div className="card-body">
                <h5 className="card-title">{post.title}</h5>
                <p className="card-text">{post.comment}</p>
            </div>
        </div>
    ));
);

const PostList = ({ postItem }) => {
    return postItem.map((post) => (
        <div className="mx-auto mb-3 card w-75" key={post.id}>
            <div className="card-body">
                <h5 className="card-title">{post.title}</h5>
                <p className="card-text">{post.comment}</p>
            </div>
        </div>
    ));
}

这是工作中的example