【问题标题】:How to call function after fetch() has finishedfetch() 完成后如何调用函数
【发布时间】:2019-02-05 10:40:13
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 什么意思,等待它完成,这样你就可以对数组做点什么了?这正是您的代码所做的。
  • 是的,我将 responseJson 置于问题状态,但在 componentWillMount 中我也需要对问题做一些事情。如果你明白
  • 不,我不明白。
  • 哦,没关系,这很简单,我最近的重点是垃圾,对不起

标签: javascript react-native fetch response


【解决方案1】:

只需在类中定义函数并使用 this.{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);
  })
}

【讨论】:

  • 但是如果我使用 redux 并通过 action creators 向服务器发出请求会怎样。对服务器的请求不会发生在组件中,如果我需要对它们做一些事情,那么检查数据是否已加载最正确?例如,应用某种过滤器。使用 componentDidUpate() 吗?
  • 发出异步请求并从操作返回承诺,无论是解决还是拒绝,并在组件内的调用函数中捕获响应或错误。所以你得到了将请求与组件绑定的正确方法
【解决方案2】:

在渲染函数中添加 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>
    );
} 

【讨论】:

    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多