簡體   English   中英

如何在 React Native 中通過 GET 請求獲取圖像?

[英]How to fetch image via GET request in React Native?

我目前在loadImage()中將圖像作為 json 文件,但我正在破壞並想知道哪種模式是正確的。 要知道的另一件事是,我僅在第一次fetch之后才獲得photo_reference參數。 我正在使用 Google Maps Place Photo API。 從第一次獲取我得到一個 JSON 文件。

到目前為止我的代碼:

const CardResturant = ({ resturant }) => {
  const [isLoading, setLoading] = useState(true);
  const [info, setInfo] = useState([]);

  const [imagePlace, setImage] = useState([]);
  const [isLoadImage, setLoadImage] = useState(true);

  useEffect(() => {
    setLoading(false);
    fetch(
      `https://maps.googleapis.com/maps/api/place/details/json?place_id=${resturant.id}&key=KEY`
    )
      .then((response) => response.json())
      .then((json) => {
        setInfo(json);
        loadImage(json?.result?.photos[0].photo_reference);
      })
      .catch((error) => console.error(error))
      .finally(() => setLoading(true));
  }, []);

  const loadImage = (photo_reference) => {
    setLoadImage(false);
    fetch(
      `https://maps.googleapis.com/maps/api/place/photo?maxwidth=100&photo_reference=${photo_reference}&key=KEY`
    )
      .then((response) => response.json())
      .then((photo) => setImage(photo))
      .catch((error) => console.error(error))
      .finally(() => setLoadImage(true));
  };

  return (
    <View>
      {!isLoading ? (
        <Text>LOADING</Text>
      ) : (
        <View>
          <View>
            <Image ??help?? />
          </View>
        </View>
      )}
    </View>
  );
};

您不應該調用res.json()來解析圖像。 它應該是res.blob() 已經說過,假設您正在嘗試獲取一張圖像,您可以這樣做:

const [imagePlace, setImage] = useState(""); // initial it to an empty string
const loadImage = async (photo_reference) => {
  setLoadImage(false);
  try {
    const res = await fetch(
      `https://maps.googleapis.com/maps/api/place/photo?maxwidth=100&photo_reference=${photo_reference}&key=KEY`
    )
    const data = await res.blob();
    setImage(URL.createObjectURL(data));
  } catch (error) {
    console.error(error)
  }finally{
    setLoadImage(true)
  }
};

我使用async/await只是為了獲得更好看的代碼。 您使用then()的方法也可以。 最后將用於渲染圖像的 JSX 更改為:

{imagePlace ? (
  <Image source={{ uri: imagePlace }} style={{ width: 200, height: 200 }} />
) : (
  <></>
)}

暫無
暫無

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

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