【问题标题】:Axios doesn't GET data in React but it does in consoleAxios 不会在 React 中获取数据,但它会在控制台中获取
【发布时间】:2018-09-09 09:38:48
【问题描述】:

我的 JSON 看起来像这样

{
    "towns" :[
        {
            "id" : 0,
            "location": "Japanifornia",
            "status" : 1
        },
        {
            "id" : 1,
            "location" : "Kohonohakatsuki",
            "status" : 2
        },
        {
            "id" : 2,
            "location" : "Taxis",
            "status" : 5
        }
        ]
}

我在 React 中使用 axios 时出现问题。它应该返回这样的结果。

[
    {
        "id": 0,
        "location": "Japanifornia",
        "status": 1
    },
    {
        "id": 1,
        "location": "Kohonohakatsuki",
        "status": 2
    },
    {
        "id": 2,
        "location": "Taxis",
        "status": 5
    }
]

问题发生了,我在 React 的 componentWillMount() 中使用 axios 从 localhost:7777/towns 获取请求。 但是从未发出过请求,我检查了来自 json-server 的日志,当我加载或重新加载包含执行 GET 请求的组件的 localhost:3000 时没有发生请求。 我已经签入了从 Firefox 到节点控制台的其他应用程序。 所有应用程序都返回它应该在 React 旁边什么都不返回的东西

这是我的组件WillMount

  componentWillMount() {
    axios.get('127.0.0.1:7777/towns')
    .then((res) => res.json())
    .then((result) => this.setState({data:result,isLoading: false}))
  }

【问题讨论】:

  • 使用组件DidMount。同时检查网络选项卡并确保您正在渲染组件
  • @RIYAJKHAN 太糟糕了,没有任何改变。
  • 检查你的 JS 控制台。如果未发出请求,则存在 js 问题。
  • 在 axios 上获取 404 错误,在 fetch 上获取有效的 JSON 解析错误

标签: javascript reactjs axios


【解决方案1】:

我终于找到了解决办法!!这是因为我的愚蠢错误。

我假设结果是 {[dataHere]} 但它实际上是 [] 数组。

错误是因为结果是JS数组而不是Json数组。

【讨论】:

    【解决方案2】:

    文档建议在 componentDidMount 内部使用 Ajax 调用,在 componentWillMount 内部你可以使用 empy 数组初始化数据。我认为你从调用中得到的是一个具有属性 towns 女巫的对象,其中包含一个数组。要获取数据,请尝试使用 result.towns 设置状态。在 componentDidMount 中执行 this.setState({ towns: result.towns}) 并在 componentWillMount 中执行 this.setState({ towns: []})。在渲染方法中添加控制台日志,您应该会看到数据。

    【讨论】:

    • 嗯,我在构造函数中清除了状态。当 componentDidMount 发出请求时,axios 发送 404 错误但从未向 json-server 发出请求,但 fetch() 在有效 JSON 上返回 JSON 解析错误。
    • 您的 axios 在端口 7777 上执行 get 但服务器在端口 3000 上运行?!尝试使用其他客户端..curl 或邮递员拨打电话
    • Json-api 在 7777 但反应在 3000。我已经用 Insomnia 和浏览器打电话了。每个应用程序都返回 json 但 axios。
    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 2018-09-11
    • 2021-09-04
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多