首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React抓取不是抓取

React抓取不是抓取
EN

Stack Overflow用户
提问于 2021-02-15 09:38:48
回答 2查看 100关注 0票数 0

在我的App.js函数中,当它第一次加载时,我想获取一个网站。此网站包含.json数据。当我尝试获取网站时,控制台显示以下错误:

代码语言:javascript
复制
App.js:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch
App.JS:9 GET https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313 net::ERR_BLOCKED_BY_CLIENT
localhost:/1 Uncaught (in promise) TypeError: Failed to fetch

当我通过web浏览器访问网站时,我能够看到JSON。

我的App.js代码:

代码语言:javascript
复制
import logo from './logo.svg';
import './App.css';
import Weather from './Weather'
import React, { Component, useState  } from "react";

function App() {
  const [details, setDetails] = useState("0");
  
  fetch("https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313")
      .then(response => response.json())
      .then((data) => {
        setDetails(data)
        console.log("hi")
      } );
    
  return (
    <div className="App">
      <div className="weatherWrap">
        <Weather longg="0" lat="0" name="China"/>
      </div>
    </div>
  );
}

export default App;

我假设我获取的网站是错误的。我还认为,按照我的方式,它每次都会继续获取。而我只想让它获取一次。请告诉我怎么修。谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-15 12:03:37

试试下面这段代码:

代码语言:javascript
复制
const url = 'https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313';

function App() {

const [details, setDetails] = useState([]);
const getDetails = async()=>{
     const response = await fetch(url);
     const details = await response .json();
     setDetails(details );
}

  useEffect(() => {
    getDetails();
  },[]);

}
票数 1
EN

Stack Overflow用户

发布于 2021-02-15 11:44:19

以下是为您工作的代码。Link

导入"./styles.css";从“react”导入{ useEffect,useState };

代码语言:javascript
复制
export default function App() {
  const [details, setDetails] = useState("0");

  useEffect(() => {
    fetch(
      "https://geolocation-db.com/json/344ec440-6bfc-11eb-a0c0-b5dee9e67313"
    )
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      });
  }, []);

  return (
    <div className="App">
      <div className="weatherWrap">hello world</div>
    </div>
  );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66201802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档