事情是:我有一个小型 react 应用程序和远程服务器(仅知道 url)。另外,我知道一些服务器方法,例如“GET/api/records” - 从服务器获取所有数据。如何通过这种方式进行通信?
我有一个按钮,它启动一个处理程序,我在其中使用 fetch。
getRecords() {
fetch("http://xxx.xxx.xxx.xxx:3000/api/records/", {method: "GET"})
.then((response) => console.log(response));
}
通过console.log,我收到一个Response对象。我如何从中获取数据?
最佳答案
从处理程序中,您可以通过响应来补充您的状态。尝试:
getRecords() {
fetch("http://xxx.xxx.xxx.xxx:3000/api/records/", {method: "GET"})
.then(response => response.json())
.then(data => {
this.setState({
yourDataKey: data
})
})
}
The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.
因此,第一个 then 会将流对象转换为 json,第二个 then 会将 json 保存在组件状态上。
关于javascript - 如何从 react 组件进行远程服务器调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57074692/