fetch()完成后如何调用函数

时间:2018-08-30 13:02:58

标签: javascript react-native fetch response

我正在使用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置于状态时,我想调用将对该数组进行处理的函数。

如果您需要更多信息,请发表评论。

谢谢!

2 个答案:

答案 0 :(得分:2)

只需在类内部定义函数,然后使用此函数调用即可。{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);
  })
}

答案 1 :(得分:0)

在渲染函数中放置一个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>
    );
}