繁体   English   中英

反应 axios 响应。json 不是 function

[英]React axios response.json is not a function

我一直收到一个错误,即 response.json 不是 function 与我的 axios 请求数据。 我不知道为什么这个代码在两天前就可以工作了......我试着搞乱承诺,看看这是否会有所作为

import React, { Component } from 'react'
import TrackingRender from '../TrackingRender/TrackingRender'
import axios from 'axios'
import { Redirect } from 'react-router';


export class OrderTracking extends Component {
    constructor() {
        super()
        this.state = {
            loadingData: true,
            order: []
        }
    }
    async componentDidMount() {
        this._isMounted = true;
        if (this.state.loadingData) {
            try {
                const { id } = this.props.match.params
                const response = await axios.get(`http://localhost:5000/api/orders/${id}`)
                const data = await response.json()
                this.setState({
                    order: data,
                    loadingData: false
                })
                console.log(this.state)
            } catch (err) {
                console.log(err)
            }
        }

    }
    render() {
        if (!this.state.loadingData) {
            return (
                <div>
                    < TrackingRender order={this.state.order} />
                </div>
            )
        } else {
            return (
                <Redirect to='/orders' />
            )
        }

    }
}

export default OrderTracking


使用 Axios 您无需运行response.json()即可获得原始响应。

数据应该在response.data中可用

要从axios获取数据,您需要使用response.data

async componentDidMount() {
        this._isMounted = true;
        if (this.state.loadingData) {
            try {
                const { id } = this.props.match.params
                const response = await axios.get(`http://localhost:5000/api/orders/${id}`)
                const data = await response.data
                this.setState({
                    order: data,
                    loadingData: false
                })
                console.log(this.state)
            } catch (err) {
                console.log(err)
            }
        }

    }

您无需在axios响应上调用 .json .json() 它已经被解析了。 您可以从response.data获取响应正文的值。

const response = await axios.get(`http://localhost:5000/api/orders/${id}`)

this.setState({
   order: response.data,
   loadingData: false
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM