fetch() 完成后如何调用函数
How to call function after fetch() has finished
我正在使用 react-native 并且我有一个获取数组的 GET 请求。现在我需要这个 fetch() 来完成获取那个数组,这样我就可以调用一个函数来处理这个数组并对它做一些事情。我如何等待它完成?
这是我的要求:
componentWillMount(){
console.log("will mount");
fetch('SOME_API', {
method: "GET",
headers: {
Accept: 'text/javascript',
'Content-Type': 'text/javascript',
}
}).then(response => response.json()).then(responseJson => {
this.setState(function (prevState, props) {
return {questions: responseJson, loading: false}
})
})
}
当此获取请求将 responseJson 置于状态时,我想调用我的函数来对该数组执行某些操作。
如果您需要更多信息,请发表评论。
谢谢!
只需在 class 中定义函数并使用它调用该函数。{function_name} 如下所示。
myFunction(responseJson) {
// ... Your code ...
}
componentWillMount() {
console.log("will mount");
fetch(baseUrl + 'api/Customer/GetCustomerAccount/' + value, {
method: 'GET',
})
.then((response) => response.json())
.then((responseJson) => {
this.myFunction(responseJson);
})
}
在渲染函数中加入 if 语句:
render(){
if(this.state.loading){
return(
<View style={{flex: 1, padding: 20}}>
// Your code if fetch() still fetching
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
// Your code if fetch() has ended
// the complete fetched data is this.state.questions
</View>
);
}
我正在使用 react-native 并且我有一个获取数组的 GET 请求。现在我需要这个 fetch() 来完成获取那个数组,这样我就可以调用一个函数来处理这个数组并对它做一些事情。我如何等待它完成?
这是我的要求:
componentWillMount(){
console.log("will mount");
fetch('SOME_API', {
method: "GET",
headers: {
Accept: 'text/javascript',
'Content-Type': 'text/javascript',
}
}).then(response => response.json()).then(responseJson => {
this.setState(function (prevState, props) {
return {questions: responseJson, loading: false}
})
})
}
当此获取请求将 responseJson 置于状态时,我想调用我的函数来对该数组执行某些操作。
如果您需要更多信息,请发表评论。
谢谢!
只需在 class 中定义函数并使用它调用该函数。{function_name} 如下所示。
myFunction(responseJson) {
// ... Your code ...
}
componentWillMount() {
console.log("will mount");
fetch(baseUrl + 'api/Customer/GetCustomerAccount/' + value, {
method: 'GET',
})
.then((response) => response.json())
.then((responseJson) => {
this.myFunction(responseJson);
})
}
在渲染函数中加入 if 语句:
render(){
if(this.state.loading){
return(
<View style={{flex: 1, padding: 20}}>
// Your code if fetch() still fetching
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
// Your code if fetch() has ended
// the complete fetched data is this.state.questions
</View>
);
}