如何使用FlatList和JSON数据呈现数百张图像的列表

时间:2018-12-31 19:01:50

标签: json reactjs api react-native

嗨,我想学习如何通过此JSON映射()并获取每个图像的href并将其放置到FlatList中?

当前我要获取的信息是collection.items.links [0] .href,并希望将此href放入Image uri

问题是我可以轻松地抓取一张图像并将其放置到FlatList中,但是无法弄清楚如何使用FlatList抓取所有图像并渲染数百张图像列表。这是因为此时似乎我需要使用map():

collection.items map()链接[0] .href

先谢谢您!

Json示例

{
  "collection": {
    "links": [
      {
        "prompt": "Next",
        "rel": "next",
        "href": "https://images-api.nasa.gov/search?media_type=image&q=moon&page=2"
      }
    ],
    "version": "1.0",
    "metadata": {
      "total_hits": 6726
    },
    "items": [
      {
        "links": [
          {
            "render": "image",
            "rel": "preview",
            "href": "https://images-assets.nasa.gov/image/PIA12235/PIA12235~thumb.jpg"
          }
        ],
        "data": [
          {
            "nasa_id": "PIA12235",
            "secondary_creator": "ISRO/NASA/JPL-Caltech/Brown Univ.",
            "keywords": [
              "Moon",
              "Chandrayaan-1"
            ],
            "date_created": "2009-09-24T18:00:22Z",
            "media_type": "image",
            "title": "Nearside of the Moon",
            "description_508": "Nearside of the Moon",
            "center": "JPL",
            "description": "Nearside of the Moon"
          }
        ],
        "href": "https://images-assets.nasa.gov/image/PIA12235/collection.json"
      },
      {
        "links": [
          {
            "render": "image",
            "rel": "preview",
            "href": "https://images-assets.nasa.gov/image/PIA13517/PIA13517~thumb.jpg"
          }
        ],
        "data": [
          {
            "nasa_id": "PIA13517",
            "secondary_creator": "NASA/GSFC/Arizona State University",
            "keywords": [
              "Moon",
              "Lunar Reconnaissance Orbiter LRO"
            ],
            "date_created": "2010-09-10T22:24:40Z",
            "media_type": "image",
            "title": "Color of the Moon",
            "description_508": "Color of the Moon",
            "center": "JPL",
            "description": "Color of the Moon"
          }
        ],
        "href": "https://images-assets.nasa.gov/image/PIA13517/collection.json"
      },
      {
        "links": [
          {
            "render": "image",
            "rel": "preview",
            "href": "https://images-assets.nasa.gov/image/PIA12233/PIA12233~thumb.jpg"
          }
        ],
        "data": [
          {
            "nasa_id": "PIA12233",
            "secondary_creator": "NASA/JPL-Caltech",
            "keywords": [
              "Moon",
              "Chandrayaan-1"
            ],
            "date_created": "2009-09-24T18:00:20Z",
            "media_type": "image",
            "title": "Mapping the Moon, Point by Point",
            "description_508": "Mapping the Moon, Point by Point",
            "center": "JPL",
            "description": "Mapping the Moon, Point by Point"
          }
        ],
        "href": "https://images-assets.nasa.gov/image/PIA12233/collection.json"
      },
      {
        "links": [
          {
            "render": "image",
            "rel": "preview",
            "href": "https://images-assets.nasa.gov/image/PIA12228/PIA12228~thumb.jpg"
          }
        ],
        "data": [
          {
            "nasa_id": "PIA12228",
            "secondary_creator": "NASA/JPL-Caltech/USGS",
            "keywords": [
              "Moon",
              "Cassini-Huygens"
            ],
            "date_created": "2009-09-24T18:00:15Z",
            "media_type": "image",
            "title": "Cassini Look at Water on the Moon",
            "description_508": "Cassini Look at Water on the Moon",
            "center": "JPL",
            "description": "Cassini Look at Water on the Moon"
          }
        ],
        "href": "https://images-assets.nasa.gov/image/PIA12228/collection.json"
      },

这也是我的代码:

export default class ThirdScreen extends React.Component {
  state = {
    search: "",
    data: "",
  }

  fetchNasa = () => {
    const {search} = this.state;

    fetch(`https://images-api.nasa.gov/search?q=${search}&media_type=image`)
    .then((response) => response.json())
    .then((result) => this.setState({
      data: result.collection.items[0].links[0].href
    }))

  }




  renderItem = ({item}) => {
    return ( 

        <View>
          <TouchableOpacity 
            style={{margin: 5, backgroundColor: 'black', padding: 15}}
          >
          <Image 
            source={{uri: this.state.data}}
            style={{width: 60, height: 60}}
          />  
          </TouchableOpacity>
        </View>
    )
  }

    render() {
      const {data} = this.state
      return (
        <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <FlatList
          data={data}
          renderItem={this.renderItem}
          keyExtractor={(item, index) => index.toString()}
        />
        </View>
      );
    }
  }

1 个答案:

答案 0 :(得分:1)

在JavaScript中,Array.map()接受一个函数,该函数接受原始数组的每个项目并返回替换它的新项目。您可以使用它将数组从一种结构转换为另一种结构。例如,您可以将帖子中的JSON数据从其原始的复杂形式转换为简单的HREF字符串数组:

const data = result.collection.items.map(eachItem => {
    return Array.isArray(eachItem.links) && eachItem.links[0] && eachItem.links[0].href
});

现在将类似的内容插入到fetchNasa函数中,以使处于状态的data变量是代表HREF的字符串数组:

fetchNasa = () => {
  const {search} = this.state;
  fetch(`https://images-api.nasa.gov/search?q=${search}&media_type=image`)
    .then((response) => response.json())
    .then((result) => this.setState({
      data: result.collection.items.map(eachItem => {
        return Array.isArray(eachItem.links) && eachItem.links[0] && eachItem.links[0].href
      })
    }));
}

最后,renderItem应该使用传递给它的项目作为参数,以返回要渲染的内容。实际上,renderItem本质上是Array.map函数的一个版本:它接受原始数据结构的每一项,并返回某种React元素进行渲染:

renderItem = ({item}) => {
  return ( 
    <View>
      <TouchableOpacity 
        style={{margin: 5, backgroundColor: 'black', padding: 15}}
      >
      <Image 
        source={{uri: item}}
        style={{width: 60, height: 60}}
      />  
      </TouchableOpacity>
    </View>
  )
}

由于this.state.data数组中的每一项都是代表HREF的字符串,因此您可以将其作为URI直接传递到<Image>源prop中。