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});
        });

    },

クロム反応ツールでは、状態は正しいです。render メソッドで this.state.templates を呼び出しています。ただし、デフォルトでは null です

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

setState の実行後に rerender が呼び出されていないようです。また、別のルートに進むと、このコンポーネントの状態は保存されず、template:null になります。

4

1 に答える 1

0

問題は、配列を反復処理する内部の約束を作成することにあったため、1 つの要求が完了した場合にメソッドが実行されます。したがって、私は一連の約束をし、全員が成功するまで待ちます. ここに解決策があります

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 に答える