首页 文章

从React App访问API的最佳方式?

提问于
浏览
-1

使用React应用程序访问API的最佳方法是什么?该API目前在Golang中使用kami&mgo开发,用于POST / GET / DELETE请求 .

我希望能够向以下URL发出GET请求:

http://user:password@localhost:8000/api/v1/systems

在我的React应用程序上并将结果存储在state属性中:

this.state = {
    data: //store the data here
}

我还想在加载页面时加载这些数据,所以也许我应该使用componentDidMount()函数来处理这个?

我从来没有在React上使用API调用,所以我想知道这里是否有人可以告诉我一个好的方法呢?

EDIT

我正在使用React 15.3.2 .

EDIT #2

我已经看了一下fetch来处理请求,但是我已经在localhost:3000上运行了反应应用程序并且运行在localhost:8000上的api,/ api / v1 / systems将返回一个具有以下格式的JSON:

{ systems : [ //list of objects ] }

我在componentDidMount()中尝试了以下内容:

fetch(myRequest) 
  .then(result => {
    console.log(result);
    //this.setState({ data: result.json() });
    });

不太确定myRequest应该是什么(尝试使用URL的简单字符串:'http://localhost:8000/api/v1/systems ') and I' m也不确定应用程序运行的端口是否会发生冲突或其他内容 .

1 回答

  • 2

    您必须决定使用库进行API调用 . 一种简单的方法是使用 fetch ,它是现代浏览器中内置的 . 有一个polyfill来覆盖旧的 . jQuery's AJAXSuperAgent是两种选择 . 这是一个使用 fetch 的简单示例 . 您只需要更改请求的URL .

    class Example extends React.Component {
      constructor() {
        super();
        this.state = { data: {} };
      }
      componentDidMount() {
        var self = this;
        fetch('http://reqres.in/api/users')
          .then(function(response) {
            return response.json()
          }).then(function(data) {
            self.setState({ data }, () => console.log(self.state));
          });
      }
      render() {
        return (
          <div/>
        );
      }
    }
    
    ReactDOM.render(<Example/>, document.getElementById('View'));
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="View"></div>
    

相关问题