0

这是代码

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 反应工具中,状态是正确的。在渲染方法中调用 this.state.templates。但默认为空

getInitialState: function () {
    return {templates: null}
},

看起来在 setState 执行后没有调用 rerender 。此外,如果我们走另一条路线,此组件中的状态将不会保存,它将是 template:null

4

1 回答 1

0

问题在于在迭代数组中做出承诺,因此如果一个请求完成,则执行该方法。因此,我做出一系列承诺,并等待每个人都成功。这是解决方案

componentDidMount: function () {
        var self = this,
            templates;
        new Promise(function (resolve, reject) {
            API.getTemplates(function (err, result) {
                if (!err) {
                    templates = result.templates;
                    resolve();
                }
            });
        }).then(function () {
            /* for every template find his userId*/
            let copyTemplate = templates;
            let promises = [];
            for (let i = 0; i < templates.length; i++) {
                promises.push(new Promise(function (resolve, reject) {
                        API.getCompanyById(templates[i].companyId, function (err, result) {
                            if (!err) {
                                copyTemplate[i].userId = result.company.userId;
                                resolve();
                            }
                        })
                    })
                );
            }

            console.log(copyTemplate);
            templates = copyTemplate;
            return Promise.all(promises);
        }).then(function () {
            console.log("templates");
            console.log(templates);
            self.setState({templates: templates});
        });

    },
于 2016-12-05T16:30:02.530 回答