【问题标题】:How to render list of hundreds of Images using FlatList and JSON data如何使用 FlatList 和 JSON 数据呈现数百个图像的列表
【发布时间】:2019-05-28 04:10:11
【问题描述】:

您好,我想了解如何通过此 JSON 进行 map() 并获取每个图像的 href 并将其放入 FlatList 中?

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

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

collection.items ma​​p() .links[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>
      );
    }
  }

【问题讨论】:

  • 由于内存和其他资源限制,更不用说时间限制,不可能渲染一个无限列表。也许你的意思是一个未知大小的列表?
  • 更正一个未知大小的列表:)

标签: json reactjs api react-native


【解决方案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 直接传递到您的 &lt;Image&gt; 源属性中。

【讨论】:

  • 真的很感谢这么长的解释,从中学到了很多!只有一个问题,我现在收到此错误?
  • JSON Value '0' of type NSNumber cannot be converted to NSString
  • @SwiftyCON 是否表示行号?这可能与return Array.isArray(eachItem) &amp;&amp; eachItem[0] &amp;&amp; eachItem[0].href有关
  • @SwiftyCON 啊,应该是Array.isArray(eachItem.links) &amp;&amp; eachItem.links[0] &amp;&amp; eachItem.links[0].href。我已经编辑了我的答案。
猜你喜欢
  • 2019-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多