【问题标题】:Google apis nearby search cant fetch json data into react jsGoogle apis附近搜索无法将json数据获取到react js中
【发布时间】:2025-12-31 14:20:11
【问题描述】:

我试图做的是从 div 内的坐标显示附近第一个地方的名称。它只是没有显示。

这是我获取 json 的代码

  const [business1, setbusiness1] = useState(null);
  useEffect(() => {
      fetch('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8943,151.2330&radius=1000&type=restaurant&keyword=attractions&key=MyApiKey&maxprice=1000')
          .then(response => response.json())
          .then(data => 
          {
            setbusiness1(data.results[0].name)
            console.log("data", data.results)
          });
  }, []);

这是我的代码,应该显示第一个景点的名称

  <div className="DetailedDescriptionsHalfLeft">
    agenda planner will be here 
    {business1} asfasfa

  </div>

结果是div里面什么都没有输出。

我检查了控制台输出,这是错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8943,151.2330&radius=1000&type=restaurant&keyword=attractions&key=MYApiKey&maxprice=1000. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

【问题讨论】:

  • 您确定 data.results[0] 具有您期望的值吗?
  • 是的,我确定,我在这个网站上检查过。 jsonquerytool.com这是json文件:pastebin.com/C3pE3Sy1
  • 由于某种原因它只是没有输出任何东西。我的 API 调用有问题吗?
  • 你检查了 fetch 然后阻塞了吗?
  • 我该怎么做?

标签: reactjs react-native rxjs google-nearby


【解决方案1】:

您可能应该使用 async()。 这是一个很好的例子。

https://www.robinwieruch.de/react-hooks-fetch-data

【讨论】:

  • async 和 fetch 有什么区别?你能帮我看看如何用propper语法写这个吗?
  • Fetch() 将获取数据,而 async() 将等待直到数据存在。请阅读我在答案中添加的链接上的页面
  • @KMAHY 获取请求没问题,使用没有错然后阻塞
  • 获取请求正常,但它不等待响应并开始呈现 html。它需要等待响应,然后显示 html。阅读文档。