你好,我试过像这样设置 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);
返回我undefined 我收到“测试”警报
什么问题?
非常感谢
最佳答案
您可以使用回调。
下面是代码示例
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");
}
下面是绑定(bind)成功和失败回调的代码。
getCats(this.successCallBack.bind(this), this.failureCallback.bind(this));
关于android - 无法在获取 react 原生时设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40957386/