ReactJS - 从 URL 获取 json 对象数据

IT技术 json reactjs
2021-04-29 11:59:16

如何从 URL 获取数据到 ReactJS。

url 是以下类型:http : //www.domain.com/api/json/x/a/search.php?s=category

如果在浏览器中输入,将显示一个 json 对象。

我如何将它加载到 ReactJS。

首先,我开始于:

const dUrl = "http://www.the....";

console.log(dUrl);

但显然它显示的是 url 而不是内容(我将能够过滤它 - 这只是将它加载到我不知道的对象中的第一步)

编辑:我宁愿不使用 jQuery。

4个回答

尝试使用 Fetch API,这是 Facebook 推荐的。您应该避免将 jQuery 与 ReactJS 混用,并坚持使用 ReactJS 操作 DOM 的方式。

function getMoviesFromApiAsync() {
   return fetch('https://facebook.github.io/react-native/movies.json')
   .then((response) => response.json())
   .then((responseJson) => {
     return responseJson.movies;
   })
   .catch((error) => {
     console.error(error);
   });
}

或者使用异步/等待

async function getMoviesFromApi() {
  try {
    let response = await fetch('https://facebook.github.io/react-native/movies.json');
    let responseJson = await response.json();
    return responseJson.movies;
   } catch(error) {
    console.error(error);
  }
}

https://facebook.github.io/react-native/docs/network.html

我知道 URL 是用于 React Native 的文档,但这也适用于 ReactJS。

编辑:使用 fetch 进行 API 调用。

fetch(http://www.example.com/api/json/x/a/search.php?s=category)
  .then(response => response.json())
  .then((jsonData) => {
    // jsonData is parsed json object received from url
    console.log(jsonData)
  })
  .catch((error) => {
    // handle your errors here
    console.error(error)
  })

Fetch 适用于所有现代浏览器。

在 React 16 或更高版本中,可以使用以下函数:

 yourFunctionName = async() => {
    const api_call = await fetch(`yourUrl`);
    const data = await api_call.json();
    console.log(data);
    }

嗨,废土(有史以来最好的游戏,顺便说一句 - 但那是一个不同的帖子:)

最简单的方法:

使用 axios 库://cdnjs.cloudflare.com/ajax/libs/axios/0.8.1/axios.min.js

componentDidMount: function() {
    var th = this;
    this.serverRequest = 
      axios.get(this.props.source)
         .then(function(result) {    
          th.setState({
            jobs: result.data.modules
          });
       })
 }

示例 https://codepen.io/motekim/pen/RJPgRK