【问题标题】:Trouble with fetch error handling in ReactjsReactjs 中获取错误处理的问题
【发布时间】:2020-10-10 16:25:31
【问题描述】:

我正在学习如何使用 fetch 并尝试使用以下语法:

const [stuff, setStuff] = useState([]);
const request = "link-to-API";

const data = await fetch(request)
    .then(response => response.json())
    .catch(err => {
      console.log(err);
      return {} //(or [], or an empty return, or any return at all)
    })

setStuff(data.hits)

然后,作为回报,我有:

{stuff.map((element) => (
        <Thing
          title={element.label}
          link={element.url}
        />
      ))}

我想只要我的 fetch 失败,我就可以渲染一个空对象。除了,这仅在 fetch 本身有效时才有效。 React 给了我错误

"对象作为 React 子对象无效(发现:TypeError: Failed to 获取)。”

但我在网上找不到任何解决方案。我怎么能不渲染任何东西来处理错误? (这不是我要渲染的唯一部分,我只想渲染一个空的 div,而不是有条件地渲染该部分)

【问题讨论】:

    标签: javascript reactjs error-handling fetch


    【解决方案1】:

    当你使用await 时,你不能使用thencatch 方法

    async 函数中使用await 很重要

    let data = null
    try{
        const response = await fetch(request)
        data = response.json();
    } catch(err)  {
          console.log(err);
        }
    

    【讨论】:

    • 因为它是一个功能组件,所以您不能让随机返回语句不返回任何内容。返回将导致“错误:App(...): 渲染没有返回任何内容。这通常意味着缺少返回语句。或者,不渲染任何内容,返回 null。”
    【解决方案2】:

    您可以尝试删除 await 关键字,因为您正在使用 .then 数据获取部分也应该包含在 useEffect 中

    const [stuff, setStuff] = useState([]);
    const request = "link-to-API";
        
    useEffect( ()=> {
        fetch(request)
        .then(response => response.json())
        .then(data => setStuff(data.hits))
        .catch(err => {console.log(err)})
    },[])
    

    【讨论】:

    • 不返回任何东西都会出现同样的问题,我会编辑问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2019-05-10
    • 2020-09-03
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2016-02-26
    相关资源
    最近更新 更多