gpt4 book ai didi

javascript - 如何在 React-Native 中使用 fetch 在 ComponentDidMount 中执行多个 API 调用?

转载 作者:行者123 更新时间:2023-11-30 19:40:53 25 4
gpt4 key购买 nike

在我的 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();

}

关于javascript - 如何在 React-Native 中使用 fetch 在 ComponentDidMount 中执行多个 API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com