我从分页API中检索数据。因此,我想设置一个系统,一旦用户滚动70%的网页,就会获取新页面的数据。
在React中你有一个优雅的解决方案吗?
这是我的组件:
import React, { Component } from 'react';
import Card from './Card';
class Main extends Component {
constructor(props) {
super(props);
this.url = 'https://rickandmortyapi.com/api/character';
this.handleScroll = this.handleScroll.bind(this);
this.state = {
data: [],
canLoad: true,
};
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
this.fetchData();
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
};
handleScroll(event) {
// get scrollY value here and call fetchData() if scroll value > 70% of height page
};
async fetchData() {
try {
const res = await fetch(this.url);
const data = await res.json();
this.setState({ data: [...this.state.data, ...data.results] });
} catch(err) {
console.log('Fetch Error', err);
}
}
render() {
return (
<main className="cards--section">
{ this.state.data.map(Card) }
</main>
);
}
}
export default Main;
非常感谢您阅读我!
答案 0 :(得分:1)
在容器上应用滚动并获取容器的引用
使用以下逻辑获取数据。这将在到达结尾之前获取100 px的数据
container.scrollTop + container.offsetHeight&gt; container.scrollHeight - 100
import React, { Component } from 'react';
import Card from './Card';
class Main extends Component {
constructor(props) {
super(props);
this.url = 'https://rickandmortyapi.com/api/character';
this.handleScroll = this.handleScroll.bind(this);
this.state = {
data: [],
canLoad: true,
};
}
componentDidMount() {
this.fetchData();
}
componentWillUnmount() {
};
handleScroll(event) {
const container = event.currentTarget;
if(container.scrollTop + container.offsetHeight > container.scrollHeight - 100){
this.fetchData();
}
// get scrollY value here and call fetchData() if scroll value > 70% of height page
};
async fetchData() {
try {
const res = await fetch(this.url);
const data = await res.json();
this.setState({ data: [...this.state.data, ...data.results] });
} catch(err) {
console.log('Fetch Error', err);
}
}
render() {
return (
<main className="cards--section" onScroll={this.handleScroll}>
{ this.state.data.map(Card) }
</main>
);
}
}
export default Main;