考虑以下简单代码:
componentDidMount() {
this._fetchData();
}
_fetchData() {
let url = UrlFormatter() + '/api/v1/blogs/';
$.get(url, (result) => {
if (result.status === 401) {
this.setState({
error: 'Your session has expired. We cannot load data.',
});
} else {
console.log('obvs here');
this.setState({
error: null,
data: result,
}, () => {
console.log('dasddsa');
this._setUpPostCollapseStatus();
});
}
}).fail((response) => {
this.setState({
error: 'Could not fetch blogs, something went wrong.'
});
});
}
如果我们调查控制台,我们会看到:
obvs here
但是我们从来没有看到:dasddsa
,现在要么这是一个错误,要么你不能在setState
的{{1}}上调用回调函数 - 或者我在ES6失败了。
思想吗
答案 0 :(得分:1)
componentDidMount
中解析承诺并使用setState
回调的示例:
http://codepen.io/mikechabot/pen/dXWQAr?editors=0011
<强>许强>
const promise = new Promise(resolve => {
setTimeout(() => {
resolve('Fetched data!')
}, 2000)
})
<强>组件强>
componentDidMount() {
console.log('Mounting...');
promise
.then((data) => {
this.setState({ data }, () => {
console.log('Data loaded')
})
})
.catch(error => {
console.log('Error', error);
})
}
<强>控制台强>
> "Mounting..."
> "Data loaded"