如何添加一个加载更多按钮来加载来自 axios 调用的下一个 50 个请求?



现在我的代码在下面,我的代理中有URL的开头:

import React, { Component } from "react";
import axios from "axios";
class BeerList extends Component {
state = {
beers: []
};
componentDidMount() {
axios
.get(`/beers/?key=6f8f96d8bd670a389ec963899a8e958d`)
.then(res => {
console.log(res);
this.setState({ beers: res.data.data });
})
.catch(err => console.log(err));
}
render() {
return (
<ul>
{this.state.beers.map(beer => (
<li key={beer.id}>{beer.name}</li>
))}
</ul>
);
}
}
export default BeerList;

我从这个 API 获取前 50 个项目,但想在底部显示一个加载更多按钮以加载接下来的 50 个项目,依此类推。这怎么可能?

根据文档,您可以传递p查询参数来请求特定页面。

首先,您可以使用一个简单的函数(在同一文件或另一个文件中(将获取与组件隔离开来。

async function fetchBeerList(key, { page }) {
return axios
.get("https://sandbox-api.brewerydb.com/v2/", {
params: {
key,
p: page
}
})
// Pre-parse Axios' `data` nesting.
.then(({ data }) => data);
}

然后,该组件可能如下所示:

class BeerList extends Component {
state = {
beers: [],
currentPage: 0,
numberOfPages: 0
};
componentDidMount() {
// Reusing the same callback as our button
this.fetchMoreBeers();
}
componentWillUnmount() {
// Simple flag to avoid state updates if the component was unmounted before
// our fetch had the time to finish.
this._unmounted = true;
}
fetchMoreBeers = () => {
const { beerId } = this.props;
const { currentPage } = this.state;
this.setState({ isFetching: true });
fetchBeerList(beerId, { page: currentPage + 1 }).then(
this.updateBeers,
this.onFailure
);
};
onFailure = err => {
// avoid updating state on an unmounted component
if (this._unmounted) return;
this.setState({ isFetching: false, err });
};
updateBeers = ({ currentPage, numberOfPages, data }) => {
// avoid updating state on an unmounted component
if (this._unmounted) return;
this.setState(({ beers }) => ({
isFetching: false,
beers: beers.concat(data),
currentPage,
numberOfPages
}));
};
render() {
const { beers, isFetching, currentPage, numberOfPages } = this.state;
return (
<div>
<ul>
{beers.map(beer => (
<li key={beer.id}>{beer.name}</li>
))}
</ul>
{!isFetching && currentPage < numberOfPages && (
<button type="button" onClick={this.fetchMoreBeers}>
See more
</button>
)}
</div>
);
}
}

仅当页数高于当前页面索引,或者我们尚未获取时,该按钮才会显示。

它还假设您正在接收beerId作为道具。

<BeerList beerId="6f8f96d8bd670a389ec963899a8e958d" />

为了尽量减少 JSX 中的噪音,我更喜欢解构我需要的一切。

const { beers, isFetching, currentPage, numberOfPages } = this.state;

为了在我从事的项目中强制执行这一点,我们使用 eslintreact/destructuring-assignmentreact 插件规则。

除了可读性改进之外,它还确保不会发生诸如this.props.onClick()使用错误this和弄乱不可变道具之类的上下文噩梦。


阅读更多关于this._unmounted.

最新更新