【问题标题】:How do you access an object in an array with this.state in React Native?如何在 React Native 中使用 this.state 访问数组中的对象?
【发布时间】:2018-09-17 09:47:05
【问题描述】:

我正在使用 react-native-snap-carousel 并且无法访问数组中的 URL。 我可以在没有其他对象的情况下访问它们,但我需要它们来命名每个图像。

      constructor(props)
  {

    super(props);

    this.state = {
    categoriesimages: [
 {
   name: 'business 1',
   images:
     'http://www.example.com/img/venture.jpg',
 },
 {
   name: 'business 2',
   images:
     'http://www.example.com/img/venture.jpg',
 },
 {
   name: 'business 3',
   images:
     'http://www.example.com/img/venture.jpg',
 }
]

  }
 renderItem = ({ item }) => {
       return (
           <Image source={{ uri: item }} style={styles.logoStyle} />

       );
   }
<View>
                 <Carousel
                   inactiveSlideOpacity={0.6}
                   inactiveSlideScale={0.65}
                   firstItem={1}
                   sliderWidth={width}
                   itemWidth={width / 3}
                   data={this.state.categoriesimages['images']} // this is the problem
                   renderItem={this.renderItem}
                   containerCustomStyle={{ overflow: 'visible' }}
                   contentContainerCustomStyle={{ overflow: 'visible' }}
                 />
             </View>

我还是新手,无法做出原生反应,查找类似问题并没有找到正确答案。

【问题讨论】:

  • 你能显示renderItem的代码吗?
  • @0x0001 我在上面的代码中添加了

标签: reactjs react-native react-native-snap-carousel


【解决方案1】:

这里this.state.categoriesimages['images']data 参数接受array 格式。

现在您正尝试访问索引为imagescategoriesimages

因此您需要将其替换为

data={this.state.categoriesimages}

renderItem={({item}) =&gt; console.log(item.images)}

【讨论】:

    【解决方案2】:

    你可以使用地图this.state.categoriesimage.map(value =&gt; value.image)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多