【问题标题】:React JS Rest Api CallReact JS Rest Api 调用
【发布时间】:2017-04-06 17:35:45
【问题描述】:

我们制作了一个简单的应用程序,它支持对学生模型进行 CRUD 操作(按 ID 获取学生、按 ID 删除学生等)。有人可以帮助如何对端点(http://ip:port/allstudents)进行简单的restful api调用并在React UI中呈现获得的json格式吗? 我的代码如下:

import React, { Component } from 'react';
import './App.css';
class App extends Component {
Getfunction() {
<a href="http://www.stackoverflow.com/">
<button>b1</button>
</a>
}
render() {
return (
<div>
  <button id='b1'
    style={{fontSize: 20, color: 'green'}}
    onClick={() => this.Getfunction()}>
    Get!
  </button>
);
}
}

export default App;

我在哪里可以将我的 restful api 调用放到查询中?究竟如何?

【问题讨论】:

  • 谷歌一下。您可以将 fetch 用于 Rest API
  • 我在这里发布问题之前已经这样做了。但是这些例子不够清楚。我已经编辑了我的问题更准确!
  • 你可能想看看如何问好questions React 是一个用于构建用户界面的库,因此你不使用“react”来进行计算和网络调用之类的事情。随意使用诸如 async/await 之类的功能或使用 fetch 从 url 收集数据。查看 fetch developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 的文档。
  • 这是一个很常见的问题(我和我们中的许多人在使用 CRUD api 时都遇到了困难),我创建了一个库来尝试为我们所有人简化这个问题:github.com/DigitalGlobe/jetset跨度>

标签: javascript reactjs


【解决方案1】:

我建议您在生命周期方法componentDidMount 中进行 api 调用,当 api 调用返回一些数据时,将其设置为您的状态,并让您的用户界面相应地更新。

例如你的api调用方法可能是这样的-

ApiCall() {
    return $.ajax({
       url: 'http://ip:port/allstudents',      
       type: 'GET',
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
}

从服务器获取新数据后,用新数据设置状态

this.setState({data:newDataFromServer});

基本上上面的调用会返回一个 jquery promise,你可以稍后使用。

现在你想用什么方法来制作 ApiCall 就这样使用 -

class App extends Component {

 constructor() {
   this.state = {
      data : []
   }
 }
 componentDidMount()
 {
   this.getFunction();
 }

 getFunction = () => {
     this.ApiCall()
        .then(
            function(data){
              console.log(data);
              // set the state here
              this.setState({data:data});
            },
            function(error){
              console.log(error);
           }
    );
 }

 render() {
   return (
      <div>
        <button id='b1'
           style={{fontSize: 20, color: 'green'}}
           onClick={() => this.Getfunction()}>
        Get!
     </button>
     {/* Now render your data here using jsx if it is array iterate over it */}
    </div>
   );
 }
}

【讨论】:

  • 谢谢!会试试这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2017-09-05
  • 1970-01-01
  • 2020-12-23
  • 2016-01-31
  • 2021-03-11
  • 2021-10-16
相关资源
最近更新 更多