【问题标题】:Unable to render promise response to html div无法呈现对 html div 的承诺响应
【发布时间】:2018-12-12 04:25:06
【问题描述】:

我有一个 rect 组件,我在其 componentDidMount 方法下更新组件的状态变量,并且该状态变量在 render 方法中用于在 UI 上显示。但我的 div 总是空的,在控制台上我看到了错误。下面是我的组件和 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

【问题讨论】:

  • “在控制台上我看到了错误” - 你得到了什么错误?
  • 您能否在问题中包含您遇到的错误?你打电话给someApiCall 的方式看起来有点奇怪。应该是someApiCall(marker, this.state.infowindow)。您还需要从someApiCall 返回fetch
  • App.js:103 Uncaught TypeError: Cannot read property 'then' of undefined
  • @Tholle 更新了问题,someApiCall 是从 apiHelper.js 导入的
  • @Bruce_Wayne 太好了。您仍然需要从someApiCall 返回fetch,否则您将无法在someInternalMethod 中使用then

标签: javascript reactjs asynchronous promise


【解决方案1】:

确保您同时返回您的fetchresponse.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");
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2020-09-10
    • 2018-10-31
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多