[英]Cannot call callback functions on setState in componentDidMount ?? - React
Consider the following simple code: 考虑以下简单代码:
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.'
});
});
}
If we investigate the console we see: 如果我们调查控制台,将会看到:
obvs here
But we never see: dasddsa
, now either this is a bug, or you cant call a callback function on setState
in componentDidMount
- Or I fail at ES6. 但是我们再也看不到: dasddsa
,现在这是一个错误,或者您不能在componentDidMount
setState
上调用回调函数-否则我在ES6上失败。
Ideas? 想法?
Hm, I wasn't able to replicate this; 嗯,我无法复制此内容; not sure if this'll be helpful, but here's an example of resolving a promise in componentDidMount
and using the setState
callback: 不知道这是否会有所帮助,但是这里有一个在componentDidMount
中解决一个promise并使用setState
回调的示例:
http://codepen.io/mikechabot/pen/dXWQAr?editors=0011 http://codepen.io/mikechabot/pen/dXWQAr?editors=0011
promise 诺言
const promise = new Promise(resolve => {
setTimeout(() => {
resolve('Fetched data!')
}, 2000)
})
component 零件
componentDidMount() {
console.log('Mounting...');
promise
.then((data) => {
this.setState({ data }, () => {
console.log('Data loaded')
})
})
.catch(error => {
console.log('Error', error);
})
}
console 安慰
> "Mounting..."
> "Data loaded"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.