重置新数组reactjs无限滚动

reset new array reactjs infinite scroll

我已经从这个 link https://www.youtube.com/watch?v=NZKUirTtxcg&t=303 尝试了 reactjs 的无限滚动并且工作完美。但我想改善我的状况。

我制作了案例产品的无限卷轴,产品有sub_category,sub_category有一个类别。例如,我有一页按类别显示所有产品(显示所有 sub_category)。

用户可以选择产品基础sub_category(该页面显示了用户为 sub_category 选择的产品)。

我的问题是我不知道将产品变量重置为新数组以填充来自 sub_category 的产品。

我有两个组件 ListInfiteTwo.jsx 和 UseProductSearch.jsx

ListInfiteTwo.jsx

import React, { useEffect, useState, useRef, useCallback } from 'react';
import axios from 'axios';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';

import '../styleProduct.css';
import { NavbarPageListProduct, NotFoundPage, COBottomNav } from '../../../components';
import configAPI from '../../../api/configAPI';
import productAPI from '../../../api/productAPI';
import Kcard from '../../Card/Kcard';
import UseProductSearch from './UseProductSearch';

export default function ListInfiniteTwo(props) {
    const classes = useStyles();
    const [totQtyItem, setTotQtyItem] = useState(null);

    const [pageNumber, setPageNumber] = useState(1);
    const [category, setCategory] = useState(props.match.params.id);
    const [subCategory, setSubCategory] = useState(null);
    const [subCategories, setSubCategories] = useState([]);
    const [amount, setAmount] = useState(0);
    const [limit, setLimit] = useState(6);
    const [selectedSubCategory, setSelectedSubCategory] = useState('selectedSubCategory');

    const {
        loading,
        error,
        products,
        hasMore
    } = UseProductSearch(pageNumber, category, limit, subCategory)

    const observer = useRef()
    const lastProductElementRef = useCallback(node => {
        if (loading) return
        if (observer.current) observer.current.disconnect()
        observer.current = new IntersectionObserver(entries => {
            if (entries[0].isIntersecting && hasMore) {
                setPageNumber(prevPageNumber => prevPageNumber + 1)
            }
        })
        if (node) observer.current.observe(node)
    }, [loading, hasMore])

    useEffect(() => {
        let getSubCategoriesAct = configAPI.getSubCategory(kategori);

        getSubCategoriesAct.then((response) => {            
            setSubCategories(response.data)
        }).catch(error => {
            console.log(error)
        });
    },[])

    const callBackAddItemTotal = (data) => {
        setTotQtyItem(data)
    }

    const callBackDeleteItemTotal = (data) => {
        setTotQtyItem(data)
    }

    const callBackCalculateAmount = (data) => {
        setAmount(data);
    }

    const selectSubCategory = (id) => {
        setSubKategori(id)
        setPageNumber(1)
    }

    return (
        <>
            <NavbarPageListProduct 
                titleView="List Product"
                viewPrev="detailOrder"
                totalQtyItem={totQtyItem}
                cHistoryId={props.match.params.id}
            />
            <div className={classes.root}>
                <div className="css-ovr-auto">
                    <div className="css-ovr-auto">
                        <div className="css-c-1hj8">
                            <div className="css-c-2k3l">
                                {
                                    <>
                                        <div className={ selectedSubCategory === 'selectedSubCategory' ? 'css-sb-sl-top-active' : 'css-sb-sl-top'} >
                                            <div className="css-sb-sl-label">
                                                <span className="css-sb-sl-val"> All on Category </span>
                                            </div>
                                        </div>
                                        {subCategories.map((x, z) =>
                                            <div className="css-sb-sl-top" onClick={() => selectSubCategory(x._id) }>
                                                <div className="css-sb-sl-label">
                                                    <span className="css-sb-sl-val" >{x.name}</span>
                                                </div>
                                            </div>
                                        )}
                                    </>
                                }
                            </div>
                        </div>
                    </div>
                </div>

                <Grid container spacing={1}>
                    <Grid container item xs={12} spacing={1}>
                        {
                            products.length >= 1 ?
                                products.map((pr, index) =>
                                    <React.Fragment>
                                        <div ref={lastProductElementRef}></div>
                                        <Kcard
                                            ref={lastProductElementRef}
                                            product={pr}
                                            callBackAddItemTotal={callBackAddItemTotal}
                                            callBackDeleteItemTotal={callBackDeleteItemTotal}
                                            callBackCalculateAmount={callBackCalculateAmount}
                                        />
                                    </React.Fragment>
                                )
                            :
                                <NotFoundPage 
                                    content="No Products"
                                />
                        }
                    </Grid>
                </Grid>
            </div>
            <div>{loading && 'Loading...'}</div>
            <div>{error && 'Error'}</div>
            {
                amount > 0 ?
                    <COBottomNav 
                        titleBottom="Total Pay"
                        amount={amount}
                        titleBtnBottom="Process"
                        action='proces_list'
                    />
                :
                    ""
            }
        </>
    )
}

UseProductSearch.jsx

import { useEffect, useState } from 'react';
import axios from 'axios';

export default function UseProductSearch(pageNumber, category, limit, subCategory) {
    const [loading, setLoading] = useState(true)
    const [error, setError] = useState(false)
    const [products, setProducts] = useState([])
    const [hasMore, setHasMore] = useState(false)
    const [lastPage, setLastPage] = useState(0)

    useEffect(() => {
        setProducts([])
    }, [])

    useEffect(() => {
        setLoading(true)
        setError(false)
        let cancel

            if (subCategory) {
                setProducts([])
            }

            axios({
                method: 'GET',
                url: process.env.REACT_APP_API_URL + `data-product-pagination`,
                params: {
                    orderby: 'newest',
                    type: 'verify',
                    page: pageNumber,
                    limit: limit,
                    xkategori: category,
                    subkategori: subCategory,
                },
                cancelToken: new axios.CancelToken(c => cancel = c)
            }).then(res => {
                if (res.data.data) {
                    if (res.data.data.data.length > 0) {
                        setProducts(prevProducts => {
                            return [...new Set([...prevProducts, ...res.data.data.data])]
                        })
                    }
                }
                setHasMore(res.data.data.data.length > 0)
                setLoading(false)
                setLastPage(res.data.data.last_page)
            }).catch(e => {
                if (axios.isCancel(e)) return
                    setError(true)
            })
            return () => cancel()

    }, [pageNumber, category, limit, subCategory])

    return { loading, error, products, hasMore }
}

我尝试在 UseProductSearch.jsx

上添加代码
if (subCategory) {
   setProducts([])
}

当用户选择子类别显示新产品的页面基于 sub_category 时它工作,但是当我向下滚动时它会将产品重置为空数组。

感谢您的帮助...

尝试将 subCategory 作为依赖项包含在 useProductSearch 的第一个 useEffect 挂钩中。这将在子类别状态更改时重置您的数组。

useEffect(() => {
    setProducts([])
}, [subCategory])