我的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旁边应该返回的内容
这是我的componentWillMount
componentWillMount() {
axios.get('127.0.0.1:7777/towns')
.then((res) => res.json())
.then((result) => this.setState({data:result,isLoading: false}))
}
2 回答
文档建议在componentDidMount中使用Ajax调用,在componentWillMount中,你可以用empy数组初始化你的数据 . 我认为你从调用中得到的是一个带有属性的对象,包含一个数组 . 要获取数据,请尝试使用result.towns设置状态 . 在componentDidMount中执行
this.setState({ towns: result.towns})
并在componentWillMount中执行this.setState({ towns: []})
. 在render方法中添加控制台日志,您应该看到数据 .我终于找到了解决方案!!这是因为我的愚蠢错误 .
我假设结果是{[dataHere]}但它实际上是[]数组 .
发生错误,因为结果是JS数组而不是Json数组 .