我一直在研究pokedex项目,该项目使我可以显示pokecards列表。
PokemonList.js的代码如下
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import axios from "axios";
export default class PokemonList extends Component {
state = {
url: "http://pokeapi.co/api/v2/pokemon/?limit=200",
pokemon: null,
itemsCountPerPage: 20,
activePage: 1
};
async componentDidMount() {
const res = await axios.get(this.state.url);
this.setState({ pokemon: res.data["results"] });
}
render() {
console.log(this.state.pokemon);
return (
<React.Fragment>
{this.state.pokemon ? (
<div className="row">
{this.state.pokemon.map(pokemon => (
<PokemonCard
key={pokemon.name}
name={pokemon.name}
url={pokemon.url}
/>
))}
</div>
) : (
<h1>Loading Pokemon</h1>
)}
</React.Fragment>
);
}
}
我一直在尝试使用诸如https://www.npmjs.com/package/react-infinite-scroller之类的无限滚动器附加组件,但是我似乎从未使它起作用。我如何应用无限滚动一次可加载20张卡片的功能?
- - - - - - - - -编辑 - - - - - - - - - - - - - - - -
最佳答案
以下是使用此API实现无限滚动的方法:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import InfiniteScroll from "react-infinite-scroller";
export default class App extends Component {
state = {
url: "https://pokeapi.co/api/v2/pokemon/?limit=200",
pokemon: [],
itemsCountPerPage: 20,
activePage: 1
};
loadPokemon = () => {
axios
.get(this.state.url)
.then(res => {
this.setState(prevState => {
return {
pokemon: [...prevState.pokemon, ...res.data.results],
url: res.data.next
};
});
})
.catch(function(error) {
// handle error
console.log(error);
});
};
render() {
// console.log(this.state.pokemon);
return (
<React.Fragment>
{this.state.pokemon ? (
<div className="row">
<InfiniteScroll
pageStart={0}
loadMore={this.loadPokemon}
hasMore={this.state.url}
loader={
<div className="loader" key={0}>
Loading ...
</div>
}
>
{this.state.pokemon.map((pokemon, i) => (
<div
style={{ borderBottom: "1px solid", padding: "10px" }}
key={pokemon.name + i}
>
<div>{pokemon.name}</div>
<div>{pokemon.url}</div>
</div>
))}
</InfiniteScroll>
</div>
) : (
<h1>Loading Pokemon</h1>
)}
</React.Fragment>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您可以在此处的codeandbox中查看它的运行情况:
关于javascript - 如何将无限滚动添加到卡片列表? [ReactJS],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58053938/