【问题标题】:ReactJS several fetch requests with promiseReactJS 几个带有 promise 的 fetch 请求
【发布时间】:2018-07-17 12:48:13
【问题描述】:

我的应用程序中需要多个获取请求来从不同的集合中获取数据。因此,我想使用 Promise 来实现它。 我从未使用过 Promise,尽管我对 stackoverflow 和其他网站进行了研究,但我无法让它发挥作用。

基本上,我需要两个 fetch 请求,我想将这些请求的结果保存到 2 个不同的状态。

这是我现在所拥有的:

getFormData () {
    fetch('/formdata', {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
    }})
        .then(res => res.json())
}

getIcons () {
    fetch('/icons', {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
    }})
        .then(res => res.json())
}

getData () {
    return Promise.all([this.getFormData(), this.getIcons()])
}

componentDidMount () {
    this.getData()
        .then(([formdata, icons]) => {
            console.log(form + "  " + icons);
        })
         .catch(err => console.log('There was an error:' + err))
}

但这不起作用。 我还尝试将承诺放在我的 componentDidMount() 生命周期方法中,如下所示:

componentDidMount () {
    return Promise.all([this.getFormData(), this.getIcons()])
        .then(([formdata, icons]) => {
            console.log(formdata + "  " + icons);
        })
         .catch(err => console.log('There was an error:' + err))
}

但这并没有奏效。 我想将 /formdata 中的数据保存到具有相同名称的状态,图标也是如此,但在控制台中它只是返回 undefined undefined,而不是 formdata 和图标。

我的代码哪里出错了?我该如何解决?

【问题讨论】:

    标签: javascript reactjs promise


    【解决方案1】:

    只需添加到@dfsq 的答案,返回承诺后,您就可以更新每个函数中的状态:

    constructor(props) {
        super(props);
    
        this.state = {
          formData = {},
          icons: {}
        }
      }
    
    getFormData () {
        return fetch('/formdata', {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
        }})
        .then(res => res.json(
            this.setState({ formData: res.json })
        ))
    }
    
    getIcons () {
        return fetch('/icons', {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
        }})
        .then(res => res.json(
            this.setState({ icons: res.json })
        ))
    }
    

    【讨论】:

    • 非常感谢您的回复。当我尝试 console.log 状态时,它返回 json() { [native code] } 而不是我可以使用的值。您知道为什么会发生这种情况以及如何避免吗?
    • 实际上我只是设法自己修复它,这样做:.then(res => res.json()) .then(formdata => this.setState({formdata}, () => console.log(this.state.formdata)))。再次感谢您抽出宝贵时间!
    • 很高兴你解决了这个问题,我也推荐试试 postman,它是测试 AJAX 请求的好工具getpostman.com
    【解决方案2】:

    您需要从您的方法中返回 Promise 对象。到目前为止,您没有返回任何东西,所以它是隐含的undefined

    试试这个:

    getFormData () {
        return fetch('/formdata', {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
        }})
            .then(res => res.json())
    }
    
    getIcons () {
        return fetch('/icons', {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
        }})
            .then(res => res.json())
    }
    

    【讨论】:

    • 非常感谢您的回复。它现在返回 [object Object],尽管当我只有一个获取请求时,它以正确的格式返回了数据。你知道我会怎么解决吗?
    • @A.S.J [object Object] 是记录对象时字符串化的结果。执行console.log(formdata, icons); 以正确检查对象。
    • 我只是对其进行了更多测试,但当我重新加载页面时,它总是无法获取 /icons/formdata。你知道为什么会这样吗?
    • 失败时显示什么错误?详情请查看网络标签。
    • Proxy error: Could not proxy request /icons from localhost:3000 to http://localhost:3001/ (ECONNREFUSED). 对于另一个获取请求,它给了我同样的错误。我读到了这个错误,但我似乎不知道如何解决它。准确的说是当我将多个文件上传到我的页面并用 axios post 保存时出现错误。当我重新加载页面时,它给了我这个错误
    猜你喜欢
    • 2018-04-25
    • 2017-10-22
    • 2016-08-08
    • 1970-01-01
    • 2021-12-04
    • 2018-05-04
    • 2020-11-21
    • 2016-10-29
    • 2019-11-09
    相关资源
    最近更新 更多