【发布时间】:2017-04-19 16:11:07
【问题描述】:
这里是代码
componentDidMount: function () {
var self = this,
templates;
new Promise(function (resolve, reject) {
API.getTemplates(function (err, result) {
if (!err) {
templates = result.templates;
resolve();
}
});
}).then(function () {
return new Promise(function (resolve, reject) {
_.map(templates,function (template) {
console.log("template.companyId " +template.companyId);
API.getCompanyById(template.companyId, function (err, result) {
if (!err) {
template.userId = result.company.userId;
resolve();
}
})
});
});
}).then(function(){
console.log("templates");
console.log(templates);
self.setState({templates: templates});
});
},
在 chrome react 工具中,状态是正确的。 在渲染方法中调用 this.state.templates。但默认为空
getInitialState: function () {
return {templates: null}
},
看起来在 setState 执行后没有调用 rerender。此外,如果我们走另一条路线,此组件中的状态将不会保存,它将是 template:null
【问题讨论】:
-
console.log 在
setState之前触发吗? -
当你在
log里面then时,你的templates等于多少? -
在log里面然后显示
[Object, Object, Object]@BenjaminGruenbaum idk,如何查看? -
为什么不将整个
promise和setState保留在componentWillMount中。为什么要等待组件挂载? -
@JyothiBabuAraja 在发出请求之前我必须在页面上显示一些内容。