reactjs - 用 axios 读取 json 并做出反应
问题描述
我是反应初学者。我正在尝试返回 uuid 并使用我在本地主机上的 api 创建的 json。我测试了它并返回:
[
{
"uuid": "80d14a1e-fd90-4d99-bca2-5d00f0b00224",
"specific_part": {
"uuid": "20c0481a-ee4b-4afb-a9f3-b2a1ba0a5c8a",
"sku": "TestTest",
"mpn": "749328571dfaA"
},
"customer": {
"uuid": "c69c43ec-d5c0-4086-abc7-e93444db7cbd",
"name": "Electronics Super Creator"
},
"quantity": 5,
"live": false
}
]
我正在使用下面的代码:
import React, { Component } from "react";
import "./App.css";
import ListingList from "./components/ListingList";
import axios from "axios";
class App extends Component {
componentDidMount() {
axios
.get("https://localhost:8000/api/v1/c69c43ec-d5c0-4086-abc7-e93444db7cbd/?format=json")
.then(response => {
const newListings = response.data.map(c => {
return {
id: c.uuid,
live: c.live
};
});
const newState = Object.assign({}, this.state, {
listings: newListings
});
this.setState(newState);
})
.catch(error => console.log(error));
}
render() {
return (
<div className="App">
<div>{JSON.stringify(this.state)}</div>
</div>
);
}
}
export default App;
这将返回一个看起来{"listings":[]}
没有错误的空列表。知道我做错了什么吗?另外,如果您有任何资源可以最好地调试这些东西,我很想听听他们的消息!
解决方案
似乎您的 API 可能是这里的问题。你如何测试它?我遇到的唯一可能导致问题的小事是/
在您的查询参数之前(?format=json
)
根据您开发 API 的方式,可以认为它与没有/
. 所以尝试改变它:
// Old
// .get("https://localhost:8000/api/v1/c69c43ec-d5c0-4086-abc7-e93444db7cbd/?format=json")
// New
.get("https://localhost:8000/api/v1/c69c43ec-d5c0-4086-abc7-e93444db7cbd?format=json")
做一个小测试,在随机 url 上使用 axios 并自己创建数据。一切看起来都在工作。
class App extends React.Component {
componentDidMount() {
axios.get('https://cat-fact.herokuapp.com/facts')
.then(response => {
const dummyResponse = { data: [
{
"uuid": "80d14a1e-fd90-4d99-bca2-5d00f0b00224",
"specific_part": {
"uuid": "20c0481a-ee4b-4afb-a9f3-b2a1ba0a5c8a",
"sku": "TestTest",
"mpn": "749328571dfaA"
},
"customer": {
"uuid": "c69c43ec-d5c0-4086-abc7-e93444db7cbd",
"name": "Electronics Super Creator"
},
"quantity": 5,
"live": false
}
]};
const newListings = dummyResponse.data.map(c => {
return {
id: c.uuid,
live: c.live
};
});
const newState = Object.assign({}, this.state, {
listings: newListings
});
this.setState(newState);
}).catch(error => {
console.log(error)
});
}
render() {
return (
<div className="App">
<div>{JSON.stringify(this.state)}</div>
</div>
);
}
}
// Render it
ReactDOM.render(
<App/>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
推荐阅读
- batch-file - 如何使用批处理脚本重命名具有多个条件的不同子目录中的 PNG 文件?
- android - 如何使用原始文件夹中的视频而不是 videoUrl
- go - 是否有一个常见的习惯用法可以有条件地推迟资源清理错误?
- python - 正则表达式从日志文件中查找组和匹配项
- python - 正则表达式:如何匹配没有阿拉伯元音的单词?
- python - 访问 XLS 文件会发出错误 HTTP 错误 403: Forbidden
- javascript - 如何制作 2 种不同的滚动功能
- r - 如何用R中的列中的行进行计算
- python - 在 Python 包的设置中创建自定义类的实例
- javascript - audio.play() 在现有函数中工作,但不是单独的函数