为什么我总是得到未定义?我使用滚动来加载我的数据



我正在使用useEffect来链接事件滚动

const myHandle = async () => {
if (
Math.ceil(window.innerHeight + document.documentElement.scrollTop) !== document.documentElement.offsetHeight ||
isFetching
)
return;
console.log(schools) // here is undefined
};
useEffect(() => {
setSchools({
alertList: [1,2,3],
})
window.addEventListener('scroll', myHandle);
}

我总是得到未定义,是什么问题?

我不确定你的简短示例的有效性,但如果你想要正确的React Hook风格,那么

const myHandle = useCallback(async () => {
if (
Math.ceil(window.innerHeight + document.documentElement.scrollTop) !== document.documentElement.offsetHeight ||
isFetching
)
return;
console.log(schools); // here is undefined
}, [isFetching, schools]);
useEffect(() => {
setSchools({
alertList: [1,2,3],
});
window.addEventListener('scroll', myHandle);
return () => {
window.removeEventListener('scroll', myHandle);
}
}, [myHandle])

确保你定义了学校的状态,这是未定义的,这里有一个简单的钩子你可以检查我没有得到undefine

import React from "react";
import { useEffect } from "react";
export default function App() {
const [schools, setSchools] = React.useState({});//school state
const [isFetching,setisFetching]=React.useState(false); //isFetching state
const myHandle = async () => {
if (
Math.ceil(window.innerHeight + document.documentElement.scrollTop) !==
document.documentElement.offsetHeight || isFetching

) {
console.log(schools, "this is data"); // here is
return;
} else {
console.log(schools, "this is data"); // here is
}
};
useEffect(() => {
setSchools({
alertList: [1, 2, 3]
});
window.addEventListener("scroll", myHandle());
}, []);
return (
<div className="App">

</div>
);
}

这是控制台截图

最新更新