如何使用钩子加载更多数据?

时间:2019-11-08 16:51:42

标签: reactjs react-hooks

我想通过触发滚动事件来加载更多数据,但这不起作用。

代码:

const CardPage = function (props) {
    const [data, setData] = useState([]);
    const [from, setSize] = useState(1);
    const size = 10;

    function fetchData () {
        const suv = window.localStorage.getItem("suv") || "gligli-user";
        const requestId = suv + (+Date.now());
        const url = baseUrl + "/api/mainpage" + "/fetch/card";
        axios.get(url, {
            params: {
                requestId,
                size,
                from
            }
        }).then((res) => {
           const curData = [...data, ...res.data];
           //the data is always an empty array
           console.log(data, res.data);
           setData(curData);
           setSize(from + size);
        })
    }
    useEffect(() => {
        fetchData();
        window.onscroll = function() {
            const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            const scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
            const $cardWrap = document.getElementById("card-page-wrap");
            const domHeight = +window.getComputedStyle($cardWrap).height.match(/[0-9]*/)[0];
            if ((windowHeight + scrollTop) - domHeight < -20) {
                fetchData();
            }
        };
    }, [])

    return (<Fragment>
        <div className="card-page-wrap" id="card-page-wrap">
                <ul>
                    {
                        data.map((item) => {
                            return (<li><img src={item.imgSrc} alt="gligli-img" onClick={(event) => { showPicture(event) }}/></li>)
                        })
                    }
                </ul>
        </div>
    </Fragment>)
}

console打印结果如下:

[] (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
[] (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

每次,数据始终是一个空数组。

1 个答案:

答案 0 :(得分:0)

尝试使用async/await告诉我它是否解决了您的问题。您的服务器返回一个non-empty对象?

const fetchData=async()=>{

  //your existing code

try{
 const res = await axios.get(url, {
            params: {
                requestId,
                size,
                from
            }
        });

    const curData = [...data, ...res.data];
           setData(curData);
           setSize(from + size);

  } catch(err){
   console.log(err);
  }

}