首页 > 解决方案 > 滚动高度调整与无限滚动

问题描述

在“滚动”位于最底部的那一刻,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'));

标签: javascriptreactjs

解决方案


在这里,我更新了您的代码,稍微简化了一些,但主要是您的代码带有注释的关键点。

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>
    );
  }
}

推荐阅读