我目前正在將影像作為 json 檔案放入,loadImage()但我正在破壞并且想知道哪種模式是正確的。另一件要知道的是,我photo_reference只在第一個之后才得到引數fetch。我正在使用 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>
);
};
uj5u.com熱心網友回復:
您不應該呼叫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 }} />
) : (
<></>
)}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506203.html
