2017-09-17 69 views
1

帖子:请求密钥 - 阵营机错误

[ 
{ id:1, name:'post1', desc: 'post1 desc', parentId: 1 }, 
{ id:2, name:'post2', desc: 'post2 desc', parentId: 2 }, 
{ id:3, name:'post3', desc: 'post3 desc', parentId: 1 } 
] 

文章减速到来。有mapStateToProps并且可以在控制台上打印this.props.posts

我的功能:

getPosts = (idPost = 1) =>{ 
    const { posts } = this.props.posts 
    return 
     posts.filter(id => posts[id].parentId == idPost) 
     .map((key, idx) => { 
      const myPost = posts[key]; 
      return(
      <View> 
       <Text> 
       { myPost.name } 
       </Text> 
      </View> 
      ) 
     }); 
}; 

错误:Requested keys of a value that is not an object.为函数的1号线。

我在做什么错?

更新1

getPostsNew = (namePost = 'post1) =>{ 
    const { posts } = this.props.posts 

    return posts.map((key, idx) => { 
    if (key.name == namePost) { 
     return(
      <View> 
      <Text> 
       { key.name } 
      </Text> 
      </View> 
    ) 
    } else { 
     return null 
    } 
    });   
}; 
+0

它不应该是const {}职位= this.props;而不是this.props.posts?此外posts.filter会给你在回调中的每个帖子不只是id。检查你的过滤器功能。地图功能 –

回答

2

您应修改如下代码来解决这个问题:

getPosts = (idPost = 1) =>{ 
    const { posts } = this.props.posts 

    return posts.map((key, idx) => { 
     if (key.parentId === 1) { 
      return(
       <View> 
       <Text> 
        { key.name } 
       </Text> 
       </View> 
     ) 
     } else { 
      return null 
     } 
     });   
    }; 

    render() { 
    return (
     <View> 
     {this.getPosts(1)} 
     </View> 
    ); 
    } 
+0

也不起作用。我尝试了它,并在{'中包装了{key.name},但没有显示任何内容。我没有看到任何错误,但没有数据。 – Somename

+0

我把它称为'{this.getPosts()}' – Somename

+0

我更新我的答案,请测试它。 –