首页 > 解决方案 > 'this.props.tasks.map is not a function' 错误-React 错误

问题描述

将数组传递给组件时出现错误-'this.props.tasks.map is not a function'

我的 Main.js 代码

let posts = [
    {
        id: 1,
        description: "This is a task",
        status: "pending"
    },
    {
        id: 2,
        description: "This is another task",
        status: "pending"
    },
    {
        id: 3,
        description: "This is an easy task",
        status: "pending"

    }
];



class Main extends Component {
    render() {
        return <div>
            <Title title="Photowall" />
            <Photowall posts={ posts } />

        </div>
    }
}

和 Photowall.js 代码

 render() {
        return <div>
            {this.props.posts.map((item) => <Photo key={item} post={item}/>)}
             </div>

    }

标签: reactjsreduxreact-redux

解决方案


你必须posts像下面这样通过。

<Photowall posts={posts} />

Photowall.js
你必须通过key={item.id},我想这会起作用。

 render() {
        return <div>
            {this.props.posts.map((item) => <Photo key={item.id} post={item}/>)}
             </div>

    }

照片

class Photo extends Component { 
   render() { 
        const data = this.props.post; 
        return <p>{data.description}</p> 
    } 
}


如果您像这样通过,{{ posts }}那么它将在另一端被视为如下。

{
   posts: [
    {
        id: 1,
        description: "This is a task",
        status: "pending"
    },
    {
        id: 2,
        description: "This is another task",
        status: "pending"
    },
    {
        id: 3,
        description: "This is an easy task",
        status: "pending"

    }
]
}

所以这就是为什么这不起作用。

希望这对你有用!


推荐阅读