javascript 在 React Native 中循环 Json 和显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34252982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:26:26  来源:igfitidea点击:

Looping Json & Display in React Native

javascriptjsonreactjsreact-native

提问by CodeGuru

How do I go about looping the result i retrieved from Json? enter image description here

我如何循环我从 Json 中检索到的结果? 在此处输入图片说明

render: function() {
     console.log(this.state.list);
     contents = (
      <View style={ styles.content }>
        <Text>Loaded</Text>

      </View>
     )
     return (
      <View style={ styles.container }>
        <View style={ styles.header }>
        <Text style={ styles.headerText }>XXX</Text>
        </View>
        <View style={ styles.content }>
            { contents }
        </View>
      </View>
    );
  }

回答by TrungDQ

React can render an array of Elements, so you just need to construct an array and assign it to your contentsvariable. I made an example using map.

React 可以渲染一个 Elements 数组,因此您只需要构造一个数组并将其分配给您的contents变量即可。我用map.

render: function() {
     console.log(this.state.list);
     contents = this.state.list.results.map(function (item) {
        return (
          <View key={item.user.email} style={ styles.content }>
            <Text>{item.user.email}</Text>
          </View>
        );
     });
     return (
      <View style={ styles.container }>
        <View style={ styles.header }>
        <Text style={ styles.headerText }>XXX</Text>
        </View>
        <View style={ styles.content }>
            { contents }
        </View>
      </View>
    );
  }

And also: when you have an array of elements in React, you should provide a unique keyattribute to each element in the array. See why. In this case, I use item.user.emailas the unique identifier, but you can use another attribute, just make sure it unique (item.user.md5is promising)

还有:当你在 React 中有一个元素数组时,你应该为key数组中的每个元素提供一个唯一的属性。看看为什么。在这种情况下,我item.user.email用作唯一标识符,但您可以使用另一个属性,只需确保它是唯一的(item.user.md5很有希望)