【问题标题】:Requested keys of a value that is not an object - React Native error非对象值的请求键 - React Native 错误
【发布时间】:2018-02-25 21:00:07
【问题描述】:

帖子:

[
 { 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  }
]

来自 reducer 的帖子。有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
    }
  });         
};

【问题讨论】:

  • 不应该是 const { posts } = this.props;而不是 this.props.posts?此外,posts.filter 会在回调中为您提供每个帖子,而不仅仅是 id。还要检查您的过滤器功能。地图功能也是如此

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


【解决方案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>
    );
  }

【讨论】:

  • 不起作用。我尝试了它并将 { key.name } 包装在 &lt;Text&gt; 中,但没有显示任何内容。我没有看到任何错误,但也没有数据。
  • 我称它为{ this.getPosts() }
  • 有效!万分感谢!我原来的功能有什么问题?
  • 很高兴为您提供帮助。 filter 函数无法正常工作,您应该注意到 map 函数迭代数组并且 map 函数的第一个参数(在本例中为 key)是当前对象。
  • 最后一个问题。如果idPoststringnumber,我会怎么做?对于帖子,它将是两者之一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多