首页 > 解决方案 > 我想用 .map() 显示我的状态

问题描述

我有这样的状态:

在此处输入图像描述

我想在我的渲染中用 .map() 显示它,如下所示:

{this.state.markers.map((marker, key) => (
     <Marker
         key={key}
         coordinate={this.state.markers[marker].coordinate}
         title={this.state.markers[marker].title}
         description={this.state.markers[marker].address}
         image={require('../images/community.png')}
      />
 ))}  

但在每次测试中,我都有这样的回应:

this.state.markers.map is not a function

我怎样才能做到这一点?

标签: javascriptiosreact-native

解决方案


根据您的ScreenShotthis.state.markersis not an arrayit is an Object因此您不能按原样映射它

为了映射它,您需要使用Object.keys.

生成的代码将变为

{Object.keys(this.state.markers).map((marker, key) => (
    <Marker
        key={key}
        coordinate={this.state.markers[marker].coordinate}
        title={this.state.markers[marker].title}
        description={this.state.markers[marker].address}
        image={require('../images/community.png')}
    />
))}

推荐阅读