react教程,如何利用useSyncExternalStore订阅scrollY?
发布于 作者:苏南大叔 来源:程序如此灵动~
本文还是继续案例一个react中使用useSyncExternalStore订阅外部数据的例子。本文订阅的数据源是window.scrollY,希望能够举一反三,能够明白useSyncExternalStore到底是个怎么样的函数。当然,还是先强调一下,react里面以use开头的函数,都是只能用在函数式组件里面的。

苏南大叔的程序如此灵动博客,记录苏南大叔和计算机代码的故事。测试环境:create-react-app@5.0.1,react@18.2.0,react-dom@18.2.0,node@16.14.2。
基本原理
基本原理就是监控 window.scrollY,以前的思路来说,拿个setInterval来定期获取window.scrollY即可。现在react里面的思路就是使用useSyncExternalStore,监控scroll事件,拿到window.scrollY。

在本文中,为了体现页面的熟知滚动值,这里使用Array.from().map()生成了多个占位符。这里的资料,可以参考:
在前面的文章里面,还使用useSyncExternalStore订阅过下面的事件:
redux的store: https://newsn.net/say/react-usesyncexternalstore-redux.html- 自定义的
store: https://newsn.net/say/react-usesyncexternalstore-store.html - 设备联网状况:https://newsn.net/say/react-usesyncexternalstore.html
监控代码
import { useSyncExternalStore } from "react";
function subscribe(onStoreChange) {
global.window?.addEventListener("scroll", onStoreChange);
return () =>
global.window?.removeEventListener(
"scroll",
onStoreChange
);
}
function useScrollY(getY = (id) => id) {
return useSyncExternalStore(
subscribe,
() => getY(global.window?.scrollY),
() => undefined
);
}
function ScrollY() {
const scrollY = useScrollY();
return <div>{scrollY}</div>;
}
const App = () => {
return (<>
{Array.from({ length: 100 }).map((value, index) => {
return (
<p key={index}>占位符</p>
)
})}
<div style={{ position: 'fixed', bottom: '0px', right: '0px' }}>
<ScrollY />
</div>
</>)
}
export default App;
函数的参数默认值
在自定义的useScrollY()中,有个比较罕见的参数默认值。参数名称是getY,它的默认值是(id) => id。下面两个函数定义是一致的效果:
function useScrollY(getY = (id) => id) {
//...
}function useScrollY() {
const getY = (id) => id;
//...
}window.scrollY三种写法
下面的三种写法都是一样的效果:
global.window?.scrollYglobal.window.scrollYwindow.scrollY结束语
这里还有很多react相关的经验文章,欢迎点击: