当“滚动”位于最底部时,将调用getUsers ()
函数。如何设置滚动使其不到达滑块的末端,并调用getUsers ()
函数。那将有无限滚动效果。我的意思是像这样的滚动效果:https://codesandbox.io/s/ww7npwxokk。当滚动到达底部时,它会返回。
此处的代码:https://stackblitz.com/edit/react-nq8btq
import './style.css';
import axios from 'axios';
class App extends Component {
constructor() {
super();
this.state = {
users: [],
page: 1
};
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
axios({
url: `https://jsonplaceholder.typicode.com/users`,
method: "GET"
})
.then(res => {
this.setState({
users: res.data
});
})
.catch(error => {
console.log(error);
})
}
scroll = (e) => {
const page = this.state.page;
const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
alert('bottom');
this.getUsers()
this.setState({
page: this.state.page + 1
})
}
const top = e.target.scrollTop;
if(top === 0 && page > 1) {
alert('I AM AT THE TOP');
this.setState({
page: this.state.page - 1
})
}
}
render() {
console.log(this.state.page)
console.log(this.state.users)
return (
<div>
<div onScroll={this.scroll} className="container">
<ul>
{this.state.users.map((user, index) =>
<li>
{user.name}
</li>
)}
</ul>
</div>
</div>
);
}
}
render(<App />, document.getElementById('root'));
最佳答案
在这里,我已经更新了您的代码,略有简化,但是大多数情况下您的代码都带有要点。
class App extends Component {
state = {
users: [],
page: 1
};
componentDidMount() {
this.getUsers();
}
getUsers = () => {
axios({
url: `https://jsonplaceholder.typicode.com/users`,
method: "GET"
})
.then(res => {
this.setState({
// *you must append to users in state, otherwise
// the list will not grow as the user scrolls
users: [...this.state.users, ...res.data],
page: this.state.page + 1
});
})
.catch(error => {
console.log(error);
})
}
scroll = (e) => {
// *simplified, to only handle appending to the list
// note the 50px from the bottom, adjust as required
// so that the request is made before the users reaches
// the bottom of the page under normal scrolling conditions.
if (e.target.scrollHeight - e.target.scrollTop <= e.target.clientHeight + 50) {
this.getUsers();
}
}
render() {
return (
<div onScroll={this.scroll} className="container">
<ul>
{this.state.users.map((user, index) =>
// *always add a unique key for each item
<li key={user.name}>
{user.name}
</li>
)}
</ul>
</div>
);
}
}