用户向下滚动时获取更多内容

问题描述 投票:1回答:1

一旦用户点击提交结果,我就会有一个带有搜索输入的页面。

可能有很多结果,我不想一次性加载它们,如何在鼠标移动时使用Lodash油门将更多数据提取到页面中?

这是我的反应组件:

const getContacts = async (searchString) => {
  const { data: contactsInfo} = await axios.get(`api/Contats/Search?contactNum=${searchString}`);
  return contactsInfo;
};
export default class Home extends React.Component {
  state = {
    contactsInfo: [],
    searchString: '',
  };

  handleSubmit = async () => {
    const { searchString } = this.state;
    const contactsInfo = await getContacts(searchString);
    this.setState({ contactsInfo });
  };

  onInputChange = e => {
    this.setState({
      searchString: e.target.value,
    });
  };

  onMouseMove = e => {

  };

  render() {
    const { contactsInfo, searchString, } = this.state;
    return (
          <div css={bodyWrap} onMouseMove={e => this.onMouseMove(e)}>
            <Header appName="VERIFY" user={user} />
            {user.viewApp && (
              <div css={innerWrap}>
                <SearchInput
                  searchIcon
                  value={searchString || ''}
                  onChange={e => this.onInputChange(e)}
                  handleSubmit={this.handleSubmit}
                />
                     {contactsInfo.map(info => (
                      <SearchResultPanel
                        info={info}
                        isAdmin={user.isAdmin}
                        key={info.id}
                      />
                    ))}
              </div>
            )}
            <Footer />
          </div>

    );
  }
}
reactjs
1个回答
0
投票

我认为,使用getContacts()你可以检索所有联系人,然后你只想以某种速度显示它们,比如显示前20个,然后当你到达最后一个时,再出现20个。只是问,因为这与“让我们获取前20个联系人,显示它们,以及当用户到达最后一个联系人时,获取另外20个”非常不同。

所以,如果我的第一个假设是正确的,我可以建议你使用Intersection Observer API qazxsw poi

这在像你这样的情况下非常有用(它甚至写在文档中“在页面滚动时延迟加载图像或其他内容。”)。

这个想法是你应该添加这个交点观察者,并开始观察最后一个图像:这个观察者将在屏幕上出现最后一个图像时立即运行回调(你甚至可以决定必须在的图像的百分比屏幕)。例如,您可以说,只要1px的图像出现在屏幕上,您就会添加另外20s的图像!

请注意,一旦显示另外20秒的图像,您必须观察正确的观察图像,并观察新的最后一张图像!

我还建议不要将观察者放在最后一张图像上,但可能在第三张图片上。

编辑:我不确定这会回答你的问题。如果我认为标题是“当用户向下滚动时获取更多内容”,但它实际上并没有使用鼠标悬停(即使我认为这个实现是最符合您目标的实现)。

编辑2:它去了,我添加了小提琴,这里有codepen:https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

请注意,我已经使用不同颜色的div模拟了联系人。发生的事情是,当屏幕上出现第三个最后一个联系人(div)时,状态中会添加新的联系人。现在联系人只是空对象,但您可以在https://codepen.io/Gesma94/pen/OqpOQb中运行获取或执行任何您想要的操作。这够清楚了吗? :)我也对代码进行了评论。

fetchMoreContent()
/* Just a function that create a random hex color. */
function randomColor() {
    let randomColor = '#';
    const letters = '0123456789ABCDEF';

    for (let i = 0; i < 6; i++) {
        randomColor += letters[Math.floor(Math.random() * 16)];   
    }
    
    return randomColor;
}

class Home extends React.Component {
    contactList = null; // Ref to the div containing the contacts.
    contactObserved = null; // The contact which is observed.
    intersectionObserver = null; // The intersectionObserver object.
    
    constructor(props) {
        super(props);
        
        this.contactList = React.createRef();
        this.state = {
            loading: true,
            contactsToShow: 0,
            contacts: []
        };
    }
    
    componentDidMount() {
        /* Perform fetch here. I'm faking a fetch using setTimeout(). */
        setTimeout(() => {
            const contacts = [];
            for (let i=0; i<100; i++) contacts.push({});
            
            this.setState({loading: false, contacts, contactsToShow: 10})}, 1500);
    }
    
    componentDidUpdate() {
        if (!this.state.loading) this.handleMoreContent();
    }
    
    render() {
        if (this.state.loading) {
            return <p>Loading..</p>
        }
        
        return (
            <div ref={this.contactList}>
                {this.state.contacts.map((contact, index) => {
                    if (index < this.state.contactsToShow) {
                        const color = contact.color || randomColor();
                        contact.color = color;                    

                        return (
                            <div
                                className="contact"
                                style={{background: color}}>
                                {color}
                            </div>
                        );
                    }
                    
                })}
            </div>
            
        );
    }

    handleMoreContent = () => {
        /* The third last contact is retrieved. */
        const contactsDOM = this.contactList.current.getElementsByClassName("contact");
        const thirdLastContact = contactsDOM[contactsDOM.length - 3];

        /* If the current third last contact is different from the current observed one,
         *  then the observation target must change. */
        if (thirdLastContact !== this.contactObserved) {
            /* In case there was a contact observed, we unobserve it and we disconnect the
             *  intersection observer. */
            if (this.intersectionObserver && this.contactObserved) {
                this.intersectionObserver.unobserve(this.contactObserved);
                this.intersectionObserver.disconnect();
            }
            
            /* We create a new intersection observer and we start observating the new third
             *  last contact. */
            this.intersectionObserver = new IntersectionObserver(this.loadMoreContent, {
                root: null,
                threshold: 0
            });
        
            this.intersectionObserver.observe(thirdLastContact);
            this.contactObserved = thirdLastContact;
        }
    }
    
    loadMoreContent = (entries) => {
         entries.forEach(entry => {
            if (entry.isIntersecting) {
                let contactsCounter = this.state.contacts.length;
                let contactsToShow = this.state.contactsToShow + 10;
        
                if (contactsToShow > contactsToShow) contactsToShow = contactsToShow;
        
                this.setState({contactsToShow});
            }
        })
        
    }
}

ReactDOM.render(<Home />, document.getElementById('root'));
@import url(https://fonts.googleapis.com/css?family=Montserrat);

body {
    font-family: 'Montserrat', sans-serif;
}

.contact {
    width: 200px;
    height: 100px;
    border: 1px solid rgba(0,0,0,0.1);
}

.contact + .contact {
    margin-top: 5px;
}
© www.soinside.com 2019 - 2024. All rights reserved.