无法设置fetch的状态反应原生

时间:2016-12-04 09:54:47

标签: android react-native fetch

您好我尝试在fetch调用上设置状态,如下所示:

    getCats() {
        fetch(GLOBALS.API + '/specials.php?action=getCats&key=' + GLOBALS.KEY)
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState = ({
                dataSource: "test"
            });
Alert.alert("test");

        })
        .catch((error) => {
            console.log(error.toString());
        });
    }

    componentDidMount() {
        this.getCats();
        console.log(this.state.dataSource);
    }

但行:

console.log(this.state.dataSource);

让我不确定 我收到了“测试”的警报

问题是什么?

tnx很多

2 个答案:

答案 0 :(得分:1)

Fetch是异步的,因此它会在运行then子句中的代码之前立即返回。因此,在控制台记录之前,setState不会运行。

答案 1 :(得分:1)

您可以使用回调。

以下是代码示例

getCats(successCallBack, failureCallback) {
    fetch(GLOBALS.API + '/specials.php?action=getCats&key=' + GLOBALS.KEY)
        .then(
            function(response) {
                if (response.status !== 200) {
                    console.log('Looks like there was a problem. Status Code: ' +
                        response.status);
                    failureCallback();
                }
                // Examine the text in the response
                response.json().then(function(data) {
                    console.log(data)
                    successCallBack(data);
                });
            }
        )
        .catch(function(err) {
            console.log('Fetch Error :-S', err);
            failureCallback();
        });
}

以下是成功和失败回调的代码

successCallBack(data) {
     console.log(data)
}

failureCallback() {
    alert("failure");
}

以下是绑定成功和失败回调的代码。

getCats(this.successCallBack.bind(this), this.failureCallback.bind(this));