ReactJS - 从 URL 获取 json 对象数据

新手上路,请多包涵

如何从 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。

原文由 Wasteland 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 602
2 个回答

编辑:使用 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 在所有现代浏览器中都可用。

原文由 Sandesh K 发布,翻译遵循 CC BY-SA 4.0 许可协议

尝试使用 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。

原文由 Hylle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Stack Overflow 翻译
子站问答
访问
宣传栏