前几天自己写了一个简单的瀑布流:React - 实现瀑布流加载。当时的代码编写里面,其实是待优化的地方。只不过当时由于问题还没解决,就用了其它方案来代替。
因此本篇文章,就对这个问题做一个探究:闭包性和state值更改。
import React, { useEffect, useState } from 'react';
import { Row, Button } from 'antd';
const mockData = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
const App: React.FC = () => {
const [ arr, setArr ] = useState<any[]>([]);
const [ count, setCount ] = useState<number>(0);
const initData = async () => {
setArr(mockData);
};
// 页面滚动
const handleScroll = async () => {
const liveDom: any = document.getElementById('test_ljj');
const clientHeight = liveDom.clientHeight;
const scrollTop = liveDom.scrollTop;
const scrollHeight = liveDom.scrollHeight;
if (scrollTop + clientHeight === scrollHeight) {
console.log('到底了');
setCount(count + 1);
}
};
useEffect(() => {
initData();
window.addEventListener('scroll', handleScroll, true);
return () => {
window.removeEventListener('scroll', handleScroll, true);
};
}, []);
return (
<div id='test_ljj' style={{ overflow: 'auto', height: 200, width: 200 }}>
{arr?.map((item, index) => {
return <Row style={{ marginTop: 10 }} key={`index_${index}`}>AAAAAAA</Row>;
})}
Count:{count}
<Button onClick={() => {
console.log(count);
setCount(count + 1);
}} type='primary'>Button</Button>
</div>
);
};
export default App;
页面效果如下:

可见:
count这个state值进行了更改,同时页面也会进行展示。然而这个count变更为1之后就没有在改变过。说明对应的Hook没起作用。Button按钮,同样进行setCount(count + 1);操作,发现值能正常的更新并完成渲染。count值依旧是0。这里就可以观测到,监听器相关的代码部分是不是形成了闭包?为什么会有这样的现象呢?我们来分析下。
我们看案例代码中的关键部分:
useEffect(() => {
initData();
window.addEventListener('scroll', handleScroll, true);
return () => {
window.removeEventListener('scroll', handleScroll, true);
};
}, [ ]);
我们知道,useEffect的第二个参数传了一个空数组,因此里面的函数只会执行一次。这个useEffect形成了一个闭包,只在组件第一次渲染的时候执行。
既然是闭包的话:
count变量,是从外部作用域拿到的。useEffect执行了一次,那它的执行结果以及当前状态下各个state的状态都已经规定好了,并不会被改变。count值,都不会改变。(因为结果在第一次执行的时候就已经决定了)对于Button按钮:
setCount触发了组件重新渲染。App函数会重新执行,此时通过useState拿到最新的count值为2。userEffect并不会执行第二次,所以useEffect内的监听器拿到的count始终是第一次渲染时,生成的作用域中count对象的值。也就是0。因此我们这么更改代码即可:
useEffect(() => {
initData();
window.addEventListener('scroll', handleScroll, true);
return () => {
window.removeEventListener('scroll', handleScroll, true);
};
}, [ count ]);
结果如下:

备注:
state和你的useEffect代码进行拆分。比如你可以写两个useEffect。我在上一篇文章里面,使用了全局变量loading来避免重复请求,这里采用state的方式。
在原本代码基础上,做一个梳理:
那么直接上代码:
/* eslint-disable @typescript-eslint/no-use-before-define */
import React, { useEffect, useState } from 'react';
import { Row, Col } from 'antd';
const mockData = [{}, {}, {}, {}, {}, {}, {}, {}, {}];
const App: React.FC = () => {
const [ arr, setArr ] = useState<any[]>([]);
const [ isLoading, setIsLoading ] = useState<boolean>(false);
const initData = async () => {
setArr(mockData);
};
// 数组长度2
const addData = () => {
return [{}, {}];
};
const refreshData = () => {
// 删除监听器,避免 “滚轮到达底部” 这一个动作被重复监听
window.removeEventListener('scroll', handleScroll, true);
// 三秒后再添加一个监听器,模拟一下接口的请求
setTimeout(() => {
// 结束加载状态,同时添加回监听器,这样就可以继续监听滚轮是否到底部。
setIsLoading(false);
// 获取新的数据
const newData:any = addData();
// 将新数据拼接到旧数据
setArr(preItems => [].concat(...preItems, ...newData));
window.addEventListener('scroll', handleScroll, true);
}, 2000);
};
// 页面滚动
const handleScroll = async () => {
const liveDom: any = document.getElementById('test_ljj');
const clientHeight = liveDom.clientHeight;
const scrollTop = liveDom.scrollTop;
const scrollHeight = liveDom.scrollHeight;
if (scrollTop + clientHeight === scrollHeight) {
// 刷到底部了,则进行瀑布数据的加载,同时isLoading来避免重复请求
if (!isLoading) {
setIsLoading(true);
}
}
};
// 初始化操作,页面刚进来肯定是需要一些基础数据的,有9条
useEffect(() => {
initData();
// 添加监听器
window.addEventListener('scroll', handleScroll, true);
// 页面销毁的时候,将监听器移除
return () => {
window.removeEventListener('scroll', handleScroll, true);
};
}, [ ]);
// 这里则是用于监听业务逻辑代码的,监听到isLoading的改变,同时只有为true的时候,才会加载数据
useEffect(() => {
if (isLoading) {
refreshData();
}
}, [ isLoading ]);
return (
<Row>
<Col >
<div id='test_ljj' style={{ overflow: 'auto', height: 200, width: 200 }}>
{arr?.map((item, index) => {
return <Row style={{ marginTop: 10 }} key={`index_${index}`}>AAAAAAA</Row>;
})}
</div>
</Col>
<Col>
数组长度:{arr.length}
</Col>
</Row>
);
};
export default App;
只需要注意一点:将业务代码和useEffect监听的对象进行关联。
useEffect是用来初始化操作的,这个操作只要执行一次。useEffect是用来加载瀑布流数据的,这一个步骤需要监听isLoading变量,因为闭包性。最终效果如下:

意思如下:
当然,本文想讨论的重点,还是useEffect的闭包性,大家以后注意就行,如果希望在useEffect里操作state值并得到反馈,那么请把他放到监听数组中(useEffect的第二个参数)。