【问题标题】:this.props.children.map at react native is not workingreact native 的 this.props.children.map 不起作用
【发布时间】:2018-04-12 13:32:25
【问题描述】:

我想通过从 api 获取的对象数组中传递一个对象来从父组件呈现子组件。

TypeError: this.props.posts.map 不是函数

renderPosts() {
return this.props.posts.map(post =>
  <HomeCard key={post.id} postData={post} />
    );
  }

所有组件:

class Home extends Component {
componentWillMount() {
  this.props.getUserPosts();
}

renderPosts() {
return this.props.posts.map(post =>
  <HomeCard key={post.id} postData={post} />
    );
  }


  render() {
    return (
      <View>
        <View style={{ paddingBottom: 55 }}>
            <SearchBar />
        </View>

        <ScrollView>
        {this.renderPosts()}
        </ScrollView>

      </View>
    );
  }
}

const mapStateToProps = state => {
const posts = state.homePost;
console.log('posts', posts);

return { posts };
};


export default connect(mapStateToProps, { getUserPosts })(Home);

【问题讨论】:

    标签: javascript react-native redux react-redux


    【解决方案1】:

    我怀疑这是因为当 Home 被挂载时,this.props.postsundefined(为空或您设置的任何默认值)。由于您没有向我们提供任何日志输出,因此很难判断,但这是一个非常常见的错误。

    直接的解决方法是在为减速器定义初始状态的位置或mapStateToProps 中为其提供默认值。后者看起来像这样(调整您的代码):

    const mapStateToProps = state => {
      const posts = state.homePost || [];
      console.log('posts', posts);
    
      return { posts };
    };
    

    虽然这将解决您的错误,但您需要纠正的另一件事是常见的误解,即 componentWillMount 中的任何内容都将在安装之前执行。这是不正确的,并且是这种生命周期方法(以及componentWillReceivePropscomponentWillUpdatewill be deprecated in the future 的原因之一。

    你的代码在这里:

    componentWillMount() {
      this.props.getUserPosts();
    }
    

    是异步的,因为您提到获取此数据。 getUserPosts 会触发,但不能保证在安装前完成。因此,尽管您认为 this.props.posts 会在渲染之前设置为某个值,但事实并非如此。因此,为什么您会收到 not a function 错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-19
      • 2021-03-08
      • 2018-06-20
      • 2017-12-29
      • 2017-10-14
      • 2021-11-05
      • 2016-08-12
      相关资源
      最近更新 更多