【发布时间】:2021-04-14 12:17:33
【问题描述】:
基本上我试图在 React 中渲染一个非常长的列表(可能是异步的),我只想向上和向下渲染可见条目±10。
我决定获取持有列表的组件的高度,然后计算整体列表高度/行高,以及滚动位置来决定用户滚动的位置。
在下面的例子中,SubWindow 是一个通用组件,可以保存一个列表或图片等......因此,我认为它不是计算的最佳位置。相反,我将 calc 移动到不同的组件并尝试使用 ref 代替
const BananaWindow = (props) => {
const contentRef = useRef(null)
const [contentRefHeight, setContentRefHeight] = useState(0)
useEffect(()=>setContentRefHeight(contentRef.current.offsetHeight), [contentRef])
//calc which entries to include
startIdx = ...
endIdx = ...
......
return (
<SubWindow
ref={contentRef}
title="all bananas"
content={
<AllBananas
data={props.data}
startIdx={startIdx}
endIdx={endIdx}
/>
}
/>
)
}
//this is a more general component. accepts a title and a content
const SubWindow = forwardRef((props, contentRef) => {
return (
<div className="listContainer">
<div className="title">
{props.title}
</div>
<div className="list" ref={contentRef}>
{props.content}
</div>
</div>
})
//content for all the bananas
const AllBanana = (props) => {
const [data, setData] = useState(null)
//data could be from props.data, but also could be a get request
if (props.data === null){
//DATA FETCHING
setData(fetch(props.addr).then()...)
}
return(
<Suspense fallback={<div>loading...</div>}>
//content
</Suspense>
}
问题:在BananaWindow 中,useEffect 仅在初始安装和绘画时触发。所以我最终只得到了占位符的offsetWidth。当SubWindow 的内容加载完成时,useEffect 什么都不做。
更新:尝试使用callback ref,但它仍然只显示占位符的高度。尝试调整观察者的大小。但真的希望有一个更简单/开箱即用的方法......
【问题讨论】:
-
我认为这是因为您的
useEffect在设置contentRef之后从未运行过。您可以改用 ref 回调。 (而且您的依赖项数组中可能不需要 refs) -
@c0m1t 我尝试使用来自doc 的回调引用,但它仍然不起作用......
-
我不确定我是否理解正确,但这个codesandbox 可能会有所帮助。
标签: javascript reactjs react-suspense