TypeError:无法读取未定义的反应映射函数的属性'id'

时间:2018-09-18 05:01:02

标签: reactjs flux

    Post component
    ---------------


    import React, { Component } from "react";
    import * as PostActions from "../actions/PostActions";
    import PostStore from "../store/PostStore";

    class Post extends Component {
      constructor() {
        super();
        this.loadPosts();
        this.getPosts = this.getPosts.bind(this);
        this.state = {
          post: []
        };
      }

      componentWillMount() {
        PostStore.on("change", this.getPosts);
      }

      componentWillUnmount() {
        PostStore.removeListener("change", this.getPosts);
      }

      getPosts() {
        this.setState({
          post: PostStore.getAll()
        });
      }

      loadPosts() {
        PostActions.fetchPosts();  // Action 
      }

      render() {
        const postItems = this.state.post.map(post => (
          <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.body}</p>
          </div>
        ));

        return (
          <div>
            <h1>Posts</h1>
            {postItems}
          </div>
        );
      }
    }

    export default Post;

----------------------------------------------

IN控制台     -------------------

  

未捕获的TypeError:无法读取未定义的属性“ id”           在Post.jsx:35           在Array.map()           在Post.render(Post.jsx:34)           在finishClassComponent(react-dom.development.js:13537)           在updateClassComponent(react-dom.development.js:13500)           在beginWork(react-dom.development.js:14089)           在performUnitOfWork(react-dom.development.js:16415)           在workLoop(react-dom.development.js:16453)           在HTMLUnknownElement.callCallback(react-dom.development.js:145)           在Object.invokeGuardedCallbackDev(react-dom.development.js:195)           在invokeGuardedCallback(react-dom.development.js:248)           在replayUnitOfWork(react-dom.development.js:15744)           在renderRoot(react-dom.development.js:16547)           在performWorkOnRoot(react-dom.development.js:17386)           在performWork(react-dom.development.js:17294)           在performSyncWork(react-dom.development.js:17266)           在InteractiveUpdates $ 1(react-dom.development.js:17557)

2 个答案:

答案 0 :(得分:2)

您可以这样做。

const postItems = this.state.post.map((post, id) => (
  <div key={id}>
    <h3>{post.title}</h3>
    <p>{post.body}</p>
  </div>
));

答案 1 :(得分:0)

最初,该帖子是一个空数组,因此无法对其进行映射。检查其长度,如果长度大于零,则进行映射。

您需要执行以下操作

const {post} = this.state;
const postItems = post.length > 0 && post.map(p => {
          return (<div key={p!= undefined && p.id}>
            <h3>{p!= undefined && p.title}</h3>
            <p>{p!= undefined && p.body}</p>
          </div>)
        });