【问题标题】:React Native: Write value to variable outside of a inner functionReact Native:将值写入内部函数之外的变量
【发布时间】:2016-09-28 17:38:50
【问题描述】:

我刚开始使用 react native,目前正在为我们的项目开发一个 couchdb api。我正在用 fecht 做我的休息请求。但在内部函数中,我无法将我的响应文本(json)写入我想要返回的变量。

_getDocument(pID)
{
    var result = "getDocument failed"

    var document = "https://"
        + this.connection.user + ":"
        + this.connection.password + "@"
        + this.connection.server + "/"
        + this.connection.database + "/"
        + pID;

    fetch(document)
        .then((response) => response.text())
        .then((responseText) => {

            result = responseText;
            Alert.alert('Fetch', result , [{text: 'ok'}])

        }).catch((error) => {
        console.warn(error);
    });

    Alert.alert('_getDocument', result , [{text: 'ok'}])

    return result;
}

在我的函数结束时,变量 result 的值仍然是“getDocument failed”,而不是我的 json 字符串。 我已经尝试通过调用另一个函数将我的响应文本存储在其他地方,但效果不佳。

【问题讨论】:

    标签: javascript android json react-native fetch


    【解决方案1】:

    您需要了解 异步与同步 - 在上面的代码中,您正在运行一系列同步语句 - 变量 resultdocument 的赋值,然后运行异步语句:fetch,然后使用Alertreturn 运行另外两个同步语句。

    我们将fetch() 方法称为异步方法,因为它在后台运行并且不会中断代码执行,方法是使用您正在使用的两个then() 语句JS promises,其中您传递的函数 ( response.text() 和第二个回调),将在获取请求完成处理时执行。这对于 API 调用很有意义,因为它可能需要一些时间。

    您只需要重新考虑代码的结构,可能在 promise 解析函数中使用回调:

     _getDocument(pID) {
        // Variable declarations...
    
        fetch(document)
            .then((response) => response.text())
            .then((responseText) => {
    
            result = responseText;
            Alert.alert('Fetch', result , [{text: 'ok'}])
    
            this.fetchCompleted(result)
    
        }).catch((error) => {
            console.warn(error);
        });
    }
    
    fetchCompleted (result) {
        Alert.alert('_getDocument', result , [{text: 'ok'}])
        // Do something with result
    }
    

    或者,如果您在组件中执行此操作,您可以简单地设置状态而不是运行回调:

    this.setState({
        data: result
    })
    

    【讨论】:

    • 与其在方法中运行下一个方法,不如在获得 json 响应后设置状态。这样您可能会觉得与代码的耦合度降低了。 this.setState({ 数据: 结果 })
    • 但是 fetchCompleted 不应该被访问,因为它在内部对象中并且它找不到函数
    • 然后添加对它的引用:const callback = this.fetchCompleted 并利用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多