我的 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 的日志,当我加载或重新加载 localhost:3000(其中包含执行 GET 请求的组件)时,没有发生请求。 我已经检查了从 Firefox 到节点控制台的其他应用程序。 除了 React 不返回任何内容之外,所有应用程序都返回应有的内容

这是我的组件WillMount

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

请您参考如下方法:

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

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

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!