2016-12-05 2 views
0

に約束で使用SETSTATEがChromeでコードはここcomponentDidMount

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の実行後に再レンダリングが呼び出されないようです。ヌル

+0

'setState'の前にconsole.logが起動しますか? –

+0

あなたの 'templates'は' then'の中に 'log'するとき、それは何ですか? **ログ**内の –

+0

は、 '[Object、Object、Object]'を表示します。 @BenjaminGruenbaum idk、どのようにチェックするのですか? –

答えて

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

    }, 
関連する問題