反应原生的this.props.children.map不起作用

时间:2018-04-12 13:32:25

标签: javascript react-native redux react-redux

我希望从父组件中渲染子组件,方法是从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);

1 个答案:

答案 0 :(得分:0)

我怀疑这是因为当this.props.posts被挂载时undefinedHome(空或默认设置为)。既然你没有给我们任何日志输出,那很难说,但这是一个非常常见的错误。

立即修复是为您定义缩减器的初始状态或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错误消息的原因。

相关问题