简体   繁体   中英

After concat the page scrolls back to the top

I have a list of items on a page. When I scroll to the bottom there is a "Load more" button. When I click this i get the new items and concat them to the original list:

handleLoadProducts = (append = false) => {
    this.setState({
        isLoading: true,
    });

    fetch('/products', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            filters: Object.keys(this.state.filters),
        }),
    }).then((response) => {
        response.json().then((data) => { 
            this.setState({
                products: append ? this.state.products.concat(data.data): data.data,
                isLoading: false,
                hasMore: data.data && data.data.length > 0
            }); 
        })
    }).catch((e) => {
        console.log(e, 'error');
    });
};

Then in render I have something like this:

<Products products={this.state.products} isLoading={this.state.isLoading}/>

However after this, the page scrolls back to the top. Is it possible to prevent this? ie stay where you are?

You have to make sure that state is only set once:

if(!this.state /* && !this.state.products */) {
    this.setState({ products: data });
}
else {
    this.state.products.push(data.data);
}

Not sure how the rest of your logic is that's why I added the comment around this.state.products.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM