【发布时间】:2021-12-11 05:48:22
【问题描述】:
我在 express 中创建了一个处理 get 请求的端点。从一个反应组件,我使用 axios 向所述端点发出一个 get 请求。我想将数据存储在我的 Component 类中的一个对象中,以便可以多次访问它(onComponentDidLoad、多个 onClick 事件处理程序等)。有没有办法将数据存储在 axios 承诺之外,和/或保留承诺,以便我可以在不履行承诺的情况下进行多次 .then 调用?
我尝试过使用 setState(),返回 promise,并从 get 请求中返回实际数据。
这是我现在拥有的:
constructor {
super();
this.myData = [];
this.getData = this.getData.bind(this);
this.storeData = this.storeData.bind(this);
this.showData = this.showData.bind(this);
}
// Store data
storeData = (data) => {this.myData.push(data)};
// Get data from API
getData() {
axios
.get('/someEndpoint')
.then(response => {
let body = response['data'];
if(body) {
this.storeData(body);
}
})
.catch(function(error) {
console.log(error);
});
}
showData() {
console.log(this.myData.length); // Always results in '0'
}
componentDidMount = () => {
this.getData(); // Get data
this.showData(); // Show Data
}
render() {
return(
<Button onClick={this.showData}> Show Data </Button>
);
}
编辑 我的问题是不正确的,存储承诺然后进行多个 .then 调用有效。我试过的时候格式不对。
【问题讨论】:
-
"保留承诺,以便我可以进行多次 .then 调用" - 是的,就这样做
-
@Bergi 只能使用一次。在一个 .then 调用promise之后,数据就不能再访问了。
-
没有。您可以根据同一承诺多次致电
.then()。一旦实现了承诺,就会调用回调。一个已实现的承诺确实会永远保持它的价值,它不会以某种方式“失去它”。 -
哦,你不会撒谎@Bergi
标签: javascript reactjs promise axios