React Native中使用map循环

5

我正在使用React Native开发应用程序,其中包含以下JSON:

const places = {
  "place1":{
    "title":"title 1",
    "image":"../img/image1.jpeg",
    "description":"description 1.",
  },
  "place2":{
    "title":"title 2",
    "image":"../img/image2.jpeg",
    "description":"description 2.",
  }
}; 

我希望将它输出为元素列表。我了解到要实现这个目的,需要使用map()方法。以下是我的代码:
export default class App extends Component{
  render() {
    return (
      <View style={styles.container}>
        {places.map((place) => {
            return (
              <Text>{place.title}</Text>
              <Text>{place.description}</Text>
            )
         })}
      </View>
    );
  }
}

但是它不起作用,有没有人知道我错在哪里或者我该如何实现我的目标?

4个回答

5

Places是一个对象,您不能像这样进行迭代。相反,您必须使用Object.keys获取键并遍历它们。就像这样。

Object.keys(places).map((key) => {
    return (
      <Text>{places[key].title}</Text>
      <Text>{places[key].description}</Text>
    )
 })}

4

MAP函数适用于数组,而不是对象。请将您的常量places更新为以下内容:

const places = [{
  "title":"title 1",
  "image":"../img/image1.jpeg",
  "description":"description 1.",
},{
 "title":"title 2",
 "image":"../img/image2.jpeg",
 "description":"description 2.",
}]

谢谢。享受编码。

2
我已经在这里创建了一个小吃: https://snack.expo.io/rk4f3aSnQ,其中包含解决方案。 map 函数属于 Array 类,因此无法在对象上使用。
我将对象放在项目中的 places.json 文件中。您肯定会找到一种方法来实现它。 此外,在使用 react-native 时,始终将代码作为单个组件 return,如您将在 App.js 文件中看到的代码片段所示:
render() {
    return (
        <View style={styles.container}>
          {places.map((place) =>
              <View>
                <Text>{place.title}</Text>
                <Text>{place.description}</Text>
              </View>)}
        </View>
    );
  }

1
另一种解决方案是使用扩展运算符:

...

{[...places].map((place) => {
  return (
    <Text>{place.title}</Text>
    <Text>{place.description}</Text>
  )
})}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接