使用map函数遍历要在元素中呈现的对象数组

时间:2017-09-29 02:46:17

标签: javascript reactjs react-native babel react-native-ios

我正在使用一个允许在幻灯片中渲染视图的包。

我试图通过创建一个包含文本和图像源字符串的对象数组来浏览每个视图。

我有两种方式:

创造一个。在render()方法中运行,并在页面元素内的“{this。function}”内部调用它。

&安培;

import React, { Component } from 'react'
import { View, Text, StyleSheet, Image } from 'react-native'
import { Pages } from 'react-native-pages'

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
})

export default class Walkthrough extends Component {
  render() {
    const pages = [{
      text: 'first slide',
      imageSource: './images/hello.png',
    },
    {
      text: 'second slide',
      imageSource: './images/hello.png',
    },
    {
      text: 'third slide',
      imageSource: './images/hello.png',
    }]
    return (
      <Pages>
        { pages.map(([value, index]) => {
          return (
            <View key={index}>
              <Image uri={value.imageSource} />
              <Text> {value.text} </Text>
            </View>
          )
        })}
      </Pages>
    )
  }
}

我继续收到此错误:“无效尝试构建与babel相关的非可迭代实例”。

我的babel相关依赖:

"devDependencies": {
    "babel-eslint": "^8.0.1",
    "babel-jest": "21.2.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "babel-preset-react-native": "4.0.0",
 },

2 个答案:

答案 0 :(得分:1)

您对array.map的使用会产生错误,应该是array.map(function(arrayItem, index) {}),而不是[arrayItem, index]

代码:

return (
  <Pages>
    { pages.map((value, index) => {
      return (
        <View key={index}>
          <Image uri={value.imageSource} />
          <Text> {value.text} </Text>
        </View>
      )
    })}
  </Pages>
)

答案 1 :(得分:0)

您以错误的方式访问地图功能。

<Pages>
{
    pages.map((page, index) => {
        return (
            <View key={index}>
                <Image uri={page.imageSource} />
                <Text> {page.text} </Text>
            </View>
        )
    })
}
</Pages>

array.map的文档     array.map((value,index)=&gt; {});