在state属性中调用REST API url时,如何循环通过一定数量的ID



我正在使用"Rick and Morty"REST API构建一个应用程序。在文档中,我们可以使用特定的查询字符串请求493个字符中的任何字符。

例如,下面的URL可以请求id为34和56的字符,但如果我们想一次请求更多的字符,我们必须提供数组中的所有id,总共有493个字符

https://rickandmortyapi.com/api/character/[34,56]

我有一个CardList组件,它在卡组件上循环并显示属性。

import React from "react";
import axios from "axios";
import Card from "./Card";
class CardList extends React.Component {
state = {
url: `https://rickandmortyapi.com/api/character/${[...Array(493).keys()]}`,
character: []
};
async componentDidMount() {
const res = await axios.get(this.state.url);
this.setState({
character: res.data
});
}
render() {
return (
<div>
{this.state.character.map(character => (
<Card
key={character.id}
id={character.id}
name={character.name}
status={character.status}
species={character.species}
gender={character.gender}
type={character.type ? character.type : "Unknown"}
/>
))}
</div>
);
}
}
export default CardList;

我想做的事:

我想在"状态"下写一个函数,它将数组从1填充到493,但我在哪里写函数?

我想做的事:

我尝试在状态中使用模板字符串,并编写了一个函数来创建数组的范围像低于

网址:`https://rickandmortyapi.com/api/character/${function loop(({var x=0;while(x<493({x++;return x}}}}

类似上面的内容,但我不确定是否可以在模板字符串中编写类似上面的函数。

请帮帮我。

您的示例似乎达到了您想要的效果,只是缺少了换行方括号。更改为:

const url = `https://rickandmortyapi.com/api/character/[${[...Array(493).keys()]}]`;

顺便说一句,似乎没有任何理由将其保留在该州。建议将其移动到州外的常量。

基本上你的代码是可以的。你只需要不需要保持任何状态。如果你需要计算一组不同的ID,我建议你在通过Axio发出HTTP请求之前,或者在一个方法或纯函数中运行componentDidMount()中的代码:

...
getUrl(count) {
// Array indexes start from 0 we wanna map them and add 1
// and at the end we join them with a comma `,`
const ids = Array(count).fill(null).map((_, idx) => idx +1).join(','); // '1,2,3...,300'
return `https://rickandmortyapi.com/api/character/[${ids}]`;
}
async componentDidMount() {
const res = await axios.get(this.getUrl(300));
this.setState({
character: res.data
});
}

最新更新