[英]How to fetch image via GET request in React Native?
I am currently taking the image as a json file in loadImage()
but I'm busting and would like to know which would be the right mode.我目前在loadImage()
中将图像作为 json 文件,但我正在破坏并想知道哪种模式是正确的。 Other thing to know is that I get the photo_reference
parameter only after the first fetch
.要知道的另一件事是,我仅在第一次fetch
之后才获得photo_reference
参数。 I'm using Google Maps Place Photo API.我正在使用 Google Maps Place Photo API。 From the first fetch I get a JSON file.从第一次获取我得到一个 JSON 文件。
My code so far:到目前为止我的代码:
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>
);
};
You shouldn't be calling res.json()
to parse an image.您不应该调用res.json()
来解析图像。 It should be res.blob()
.它应该是res.blob()
。 That has been said, assuming you are trying to fetch one image, you could do it like so:已经说过,假设您正在尝试获取一张图像,您可以这样做:
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)
}
};
I'm using async/await
just to have a better looking code.我使用async/await
只是为了获得更好看的代码。 Your approach with then()
would work as well.您使用then()
的方法也可以。 Finally change your JSX for rendering the image to:最后将用于渲染图像的 JSX 更改为:
{imagePlace ? (
<Image source={{ uri: imagePlace }} style={{ width: 200, height: 200 }} />
) : (
<></>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.