请求的值不是对象的键 - React Native错误

时间:2017-09-17 03:37:52

标签: reactjs react-native ecmascript-6 react-redux

帖子:

[
 { 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>
            )
        });  
};

错误:函数第1行的Requested keys of a value that is not an object.

我做错了什么?

更新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
    }
  });         
};

1 个答案:

答案 0 :(得分:1)

您应修改以下代码以解决此问题:

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>
    );
  }