我有一个rect组件,我在它的componentDidMount方法下更新了组件的状态变量,这个状态变量在render方法中用来在UI上显示。但是我的div始终是空的,并且在控制台上我看到error.Below是我的组件和js文件内容
App.js
componentDidMount () {
...
this.someInternalMethod()
}
someInternalMethod() {
someApiCall().then(result => {
this.state.divContent.setContent(result)
})
}
apiHelper.js
export function someApiCall() {
// Build the api endpoint
var url = "http://someurl";
fetch(url).then(function(response) {
if (response.status !== 200) {
return;
}
response.json().then(function(data) {
//this log is printing data after error
console.log(data);
return formattedHtmlData(data));
});
}).catch(function(err) {
console.log("Sorry data can't be loaded");
});
}
Formatter.js
export function formattedHtmlData(data) {
//do html formatting of data put inside div etc.
and return
}
不能弄清楚我错过了什么。感谢您的帮助。
PS :我已经在stackoverflow - get promise value in react component上提到了这个问题
发布于 2018-07-04 03:29:51
请确保同时返回您的fetch
和response.json()
调用,否则承诺链将被打破,并且您将无法在someInternalMethod
中使用then
。
export function someApiCall() {
// Build the api endpoint
var url = "http://someurl";
return fetch(url)
.then(function(response) {
if (response.status !== 200) {
return;
}
return response.json().then(function(data) {
//this log is printing data after error
console.log(data);
return formattedHtmlData(data);
});
})
.catch(function(err) {
console.log("Sorry data can't be loaded");
});
}
https://stackoverflow.com/questions/51161627
复制相似问题