从React App访问API的最佳方式



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

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

http://user: password@localhost: 8000/api/v1/系统

,并将结果存储在一个state属性中:

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

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

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

编辑

我使用的是React 15.3.2.

编辑# 2

我已经看了fetch来处理请求,但我仍然不确定如何在我的情况下使用它。我已经在localhost:3000上运行react应用程序,在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'),我也不确定应用程序运行的端口是否会产生冲突或其他东西。

您必须决定使用一个库来执行API调用。一种简单的方法是使用fetch,它是内置在现代浏览器中的。有一个填充物覆盖旧的。jQuery的AJAX或SuperAgent是两种选择。下面是一个使用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>

最新更新