簡體   English   中英

REACT NATIVE:如何獲取 API 數據(JSON)並插入到 Flatlist

[英]REACT NATIVE : How to fetch API data (JSON) and insert into Flatlist

大家好,我得到了 API 數據,但無法解決如何解決這個問題,也許對新生有什么建議?

在這里,我附上了我已經做過的截圖:

圖片

您列出的圖像 API 不返回 URL。 它返回 JSON,就像您最初的 API 響應一樣。 因此,您必須對圖像執行fetch請求並存儲它們,然后參考您在列表中獲得的 URL。 這將需要更多的 state。

這是一個工作示例:

export default function App() {
  const [data, setData] = React.useState(null)
  const [isLoading, setLoading] = React.useState(false)
  const [images, setImages] = React.useState({})
  
  React.useEffect(() => {
      fetch('https://dog.ceo/api/breeds/list/all')
        .then((response) => response.json())
        .then((json) => setData(Object.keys(json.message)))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false));
    }, []);

  React.useEffect(() => {
    if (!data) { return; }
    data.forEach((dataItem,index) => {
      if (index > 5) { return; }
      let url = `https://dog.ceo/api/breed/${dataItem}/images`
      fetch(url)
        .then((response) => response.json())
        .then(json => {
          if (!json.message[0]) { return; }
          setImages(prevState => ({...prevState, [dataItem]: json.message[0]            }));
        })
    })
  },[data])

    
    return (
      <View style={styles.container}>
      {isLoading ? <ActivityIndicator/> : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => index.toString()}
            renderItem={({ item }) => (
            <View>
              <Text>{item} </Text>
              {images[item] ?  <Image
               style={{width: 100, height: 100}}
                source={{
               uri: images[item],
               }}
              />  : null }
              <Text>Image: {images[item]}</Text>
            </View>)}
          />
      )
      }
      </View>
   );
}

https://snack.expo.io/5FjQnP1Xf

請注意,在此示例中,我只獲取前 5 張圖像以避免進行大量 API 調用。

它也不是一個特別強大的解決方案——在現實世界中,你肯定會比我在這里做更多的錯誤處理、緩存圖像等——這只是一個基本的概念驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM