在我的componentDidMount函数中,我调用AsyncStorage来获取一些保存的值,然后发出GET请求并获取如下所示的数据:
componentDidMount() {
AsyncStorage.getItem("token").then(value => {
const url = 'my url';
console.log('token:' + value)
return fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'token': 'abcd',
'jwt': value
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson,
isLoading: false,
getValue: value
})
})
.catch((Error) => {
console.log(Error)
})
})
}
现在,我需要再发一个GET请求。假设我想在此函数中再次发出相同的请求,我该怎么做?
我从建议的评论中很容易地解决了这个问题。我在两个不同的函数中执行了API调用部分,然后在ComponentDidMount中调用这两个函数,如下面的代码 -
getFirstApiResposnse() {
AsyncStorage.getItem("token").then(value => {
const url = 'my url';
console.log('token:'+ value)
return fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'abcd',
'jwt': value
})
})
.then((response)=> response.json() )
.then((responseJson) => {
this.setState({
dataSource: responseJson,
isLoading: false,
getValue: value
})
})
.catch((Error) => {
console.log(Error)
});
}
)
};
getSecondApiResponse() {
AsyncStorage.getItem("token").then(value => {
const url = 'my url';
console.log('token:'+ value)
return fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'abcd',
'jwt': value
})
})
.then((response)=> response.json() )
.then((responseJson) => {
console.log('####:'+responseJson.cat_note)
this.setState({
isLoading: false,
getValue: value,
})
})
.catch((Error) => {
console.log(Error)
});
}
)
}
componentDidMount() {
this.getFirstApiResponse();
this.getSecondApiResponse();
}
您也可以使用Promise.all()。这对多个请求很方便。此外,我们可以使用辅助库,如async,并根据项目需要使用forEach,waterFall,series,parallel等方法。这些东西使我们的代码更具可读性和可扩展性