reactjs - 让 Axios 限制响应的数量
问题描述
我正在尝试对 API 进行 axios GET 调用以检索一些 JSON 数据。数据存储在一个包含多个对象的数组中,每个对象都包含相同的键。这个数组中有数百个对象,但我只想返回前十个。我知道我可以在返回数据集后截断它,但我想知道是否有办法限制对我的 API 调用的响应量。
以下是数据集的示例:
[
{
"userId": 1,
"id": 1,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"userId": 1,
"id": 2,
"title": "1984",
"author": "George Orwell"
},
{
"userId": 1,
"id": 3,
"title": "The Count of Monte Cristo",
"author": "Alexandre Dumas"
},
]
我的 axios 请求也很简单:
router.get('/', (req, res) => {
axios.get(`https://jsonwebsit.info.com/posts`)
.then( response => {
res.send(response.data)
})
.catch(err => {
console.log('Error getting all data from API', err)
})
});
解决方案
实际上,您可以限制来自某个 API 端点的响应数量。
只需在发出请求时将参数作为对象添加为第二个参数。
例如:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/todos',{
params: {
_limit: 10
}
})
.then((res) => {
this.setState({
todos: res.data
});
})
}
在这里,您将来自 jsonplaceholder API 的响应限制为 10。
你也可以打电话https://jsonplaceholder.typicode.com/todos/?_limit=10
,得到同样的结果。
希望能帮助到你。
推荐阅读
- javascript - 为我的问题实现 javascript 数据操作的最快方法是什么?
- javascript - 如何从 asp.net 核心视图更新 javascript 中的模型值
- java - Java/Jackson 注释:映射数组或对象?
- rust - 使用泛型生命周期时,借来的值的寿命不够长。
- php - 如何按会议日期对由订单组成的表格进行排序
- php - PHP美化网址
- javascript - 节点 JS 错误:(发送到客户端后无法设置标头)
- ios - 为什么我在 Xcode 上移动屏幕时看到文本较晚?
- python - Python中的变量范围和名称解析
- wso2 - WSO2 EI 休息 API