我正在使用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}
})
})
}
当这个get请求将responseJson置于状态时,我想调用我的函数,该函数将对该数组执行某些操作。
如果您需要更多信息,请发表评论。
谢谢!
只需在类中定义函数并使用此函数调用函数。{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);
})
}
在render函数中放置一个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>
);
}