【发布时间】:2021-01-13 12:09:44
【问题描述】:
对于我的反应天气应用程序,我需要将代表城市的每个 Card 元素附加到该城市的 img。 除了下载很多图片,我发现谷歌地方可以给我这些信息。 我从 Google Cloud Platform 注册并获得了一个 api 密钥。
这是我的卡片组件:
附言- 在googleapi url之前来自herokuapp的https是我发现处理CORS错误的唯一解决方案
import React, { useState, useEffect } from 'react'
import Card from 'react-bootstrap/Card';
import Button from 'react-bootstrap/Button';
export default function CardUI({ apiKey, place }) {
const [photoUrl, setPhotoUrl] = useState('');
useEffect( () => {
fetch(`https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/details/
json?place_id=${place}&fields=photo&key=${apiKey}`)
.then(response =>response.json())
.then(data => {
setPhotoUrl(data);
console.log(data);
})
}, [])
return (
<Card style={{ width: '18rem' }}>
<Card.Img variant="top" src={photoUrl} />
<Card.Body>
<Card.Title>Card Title</Card.Title>
<Card.Text>
Some quick example text to build on the card title and make up the bulk of
the card's content.
</Card.Text>
<Button variant="primary">Go somewhere</Button>
</Card.Body>
</Card>
)
}
【问题讨论】:
标签: reactjs google-maps-api-3 react-hooks fetch google-places-api