繁体   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