在React中制作API过滤列表和实现无限滚动分页,可以按照以下步骤进行:
以下是一个简单的示例代码:
import React, { Component } from 'react';
class FilteredList extends Component {
constructor(props) {
super(props);
this.state = {
filter: '',
data: [],
page: 1,
pageSize: 10,
isLoading: false,
};
}
componentDidMount() {
this.fetchData();
this.attachScrollListener();
}
componentDidUpdate(prevProps, prevState) {
if (prevState.filter !== this.state.filter) {
this.fetchData();
}
}
componentWillUnmount() {
this.detachScrollListener();
}
attachScrollListener() {
window.addEventListener('scroll', this.handleScroll);
}
detachScrollListener() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = () => {
if (
window.innerHeight + window.scrollY >= document.body.offsetHeight &&
!this.state.isLoading
) {
this.setState(prevState => ({
page: prevState.page + 1,
}), this.fetchData);
}
};
fetchData = () => {
const { filter, page, pageSize } = this.state;
const url = `https://api.example.com/data?filter=${filter}&page=${page}&pageSize=${pageSize}`;
this.setState({ isLoading: true });
fetch(url)
.then(response => response.json())
.then(data => {
this.setState(prevState => ({
data: prevState.data.concat(data),
isLoading: false,
}));
})
.catch(error => {
console.error('Error fetching data:', error);
this.setState({ isLoading: false });
});
};
handleFilterChange = event => {
this.setState({ filter: event.target.value });
};
render() {
const { data, filter } = this.state;
const filteredData = data.filter(item =>
item.toLowerCase().includes(filter.toLowerCase())
);
return (
<div>
<input
type="text"
value={filter}
onChange={this.handleFilterChange}
placeholder="Filter data"
/>
<ul>
{filteredData.map(item => (
<li key={item}>{item}</li>
))}
</ul>
{this.state.isLoading && <div>Loading...</div>}
</div>
);
}
}
export default FilteredList;
这个示例代码实现了一个简单的API过滤列表和无限滚动分页功能。用户可以在输入框中输入过滤条件,列表会根据过滤条件进行筛选,并且在滚动到底部时会加载更多数据。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云