【问题标题】:Destructuring error, response from fetch()解构错误,来自 fetch() 的响应
【发布时间】:2019-12-30 22:25:13
【问题描述】:

我想通过解构从 fetch() 返回的 [responseError, response] 对象,在 React 组件中实现 Go 风格的错误处理优先数据获取。我遇到了这个错误: Uncaught (in promise) TypeError: arr[Symbol.iterator] is not a function 这是由解构语法触发的。

当我在没有解构的情况下设置它时,提取工作正常,即

const res = await fetch(APIurl) 。

我想做什么:

    let requestBody = {
      query: `
        query {
          users {
            email
          }
        }
      `
    }

    const [resError, res] = await fetch(APIurl, {
      method: 'POST',
      body: JSON.stringify(requestBody),
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + context.token
      }
    })

    if (resError || !res) {
      console.log('Request failed', resError)
      return
    }

    const [parseError, json] = await res.json()

    if (parseError || !json) {
      console.log('Request failed', parseError)
      return
    }

    const userData = json.data.users

    setUsers(userData)
  }

目前有效:

    let requestBody = {
      query: `
        query {
          users {
            email
          }
        }
      `
    }

    const res = await fetch(APIurl, {
      method: 'POST',
      body: JSON.stringify(requestBody),
      headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + context.token
      }
    })

    if (res.status !== 200 && res.status !== 201) {
      throw new Error('Fetch failed')
    }

    const json = await res.json()

    const userData = json.data.users

    setUsers(userData)
  }

我希望输出是一样的,但是解构会触发上面提到的错误。我正在尝试复制本文中提到的模式:https://www.dalejefferson.com/articles/2016-01-25-error-first-pattern-for-es7-async-await/

【问题讨论】:

  • 试试:const { parseError, json } = await res.json()
  • 使用该语法两个对象都返回未定义
  • fetch() 返回一个 Response 对象,而不是值列表。这就是错误消息所说的,返回的对象是不可迭代的。您引用的文章来自 2016 年 1 月。我不知道当时的代码是否有效,现在它与 fetch() 的规范相矛盾。也许这是在规范最终确定之前。

标签: javascript reactjs ecmascript-6 fetch


【解决方案1】:

您需要编写自己的中间件来处理您的响应。

const validate = (req) => {
  // do some magic
  return [err, res];
};
const request = fetch('/api/url');
const [err, res] = validate(request);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2021-03-18
    • 2020-09-27
    相关资源
    最近更新 更多