【问题标题】:Correct way to catch fetch errors in React?在 React 中捕获获取错误的正确方法?
【发布时间】:2017-11-03 15:17:41
【问题描述】:

我有一个简单的 react 组件,如下所示:

class Test extends React.Component {
  componentDidMount() {
    fetch('/some-url-here')
      .then((data) => {
        this.setState({ data });
      })
      .catch(() => {
        alert('failed to fetch');
      });
  }

  render() {
    // render the data here
  }
}

问题在于catch 不只是捕获获取错误。它还捕获render 中抛出的任何异常!创建一个获取一些数据并处理获取错误的简单组件的正确方法是什么?

【问题讨论】:

  • 如果将 fetch 拉出到它自己的函数中,然后在 componentDidMount 中调用它,它仍然会捕获渲染错误吗?
  • 刚试了下,还是能抓到他们
  • 如果您使用 .then 第二个回调而不是 .catchdoc
  • 我建议在尝试调试之前尝试解决渲染中的错误。如果它不能渲染,它就不能正确安装,对吧?
  • @GabrielBleu 啊,这是因为 setState 导致了渲染,所以当发生这种情况并且出现错误时,它会被传递给 catch!!

标签: javascript reactjs ecmascript-6


【解决方案1】:
class Test extends React.Component {
  componentDidMount() {
    fetch('/some-url-here')
      .then((data) => {
        this.setState({ data });
      }, (error) => {
        if (error) {
          // handle error here
        }
      });
  }

  render() {
    // render the data here
  }
}

如果您使用 catch 而不是第二个回调,则在 setState 方法期间可能发生的任何错误都将不予处理。因此,您可以以自己的方式捕获渲染方法错误。 有关更多信息,请阅读 Dan Abramov 的这条推文。

Dan's Tweet

【讨论】:

  • 实际上,我认为您的意思是将错误回调传递给.then?在then 的第一个回调中不是error 吗?
  • @Vic 是的!更正了我的代码。感谢您的警告
猜你喜欢
  • 2021-07-26
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 2020-05-05
相关资源
最近更新 更多