【发布时间】:2017-03-28 13:54:21
【问题描述】:
我使用 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 调用,所以我想知道这里是否有人能告诉我一个好的方法?
编辑
我正在使用 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'),我也不确定应用程序运行的端口是否会产生冲突或其他问题。
【问题讨论】:
标签: javascript reactjs fetch