交叉点观察者无法更新状态
我正在尝试使用“相交观察者”创建无限滚动,但是回调功能无法更新状态。当我向下滚动时,我可以看到States的Console.Log输出,但总是相同的。
import React, { useEffect, useState, useRef } from 'react';
// Css
import './index.css';
// Components
import QuadColors from './colors-components/quad-colors';
import SearchBar from '../../components/searchBar';
export default function colors() {
const [renderColorSets, setRenderColorSets] = useState(5);
const containerRef = useRef();
const footRef = useRef();
// Intersection Observer
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setRenderColorSets(renderColorSets + 1);
console.log(renderColorSets);
}
});
observer.observe(footRef.current);
}, []);
return (
<>
<SearchBar placeholder="Color" />
<div className="random-colors-container" ref={containerRef}>
{[...Array(renderColorSets)].map(() => {
return <QuadColors />;
})}
<div ref={footRef} />
</div>
</>
);
}```
I am trying to create infinite scrolling with intersection observer, but callback function fails to update state. When i scroll down i can see states's console.log output but its always same.
import React, { useEffect, useState, useRef } from 'react';
// Css
import './index.css';
// Components
import QuadColors from './colors-components/quad-colors';
import SearchBar from '../../components/searchBar';
export default function colors() {
const [renderColorSets, setRenderColorSets] = useState(5);
const containerRef = useRef();
const footRef = useRef();
// Intersection Observer
useEffect(() => {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setRenderColorSets(renderColorSets + 1);
console.log(renderColorSets);
}
});
observer.observe(footRef.current);
}, []);
return (
<>
<SearchBar placeholder="Color" />
<div className="random-colors-container" ref={containerRef}>
{[...Array(renderColorSets)].map(() => {
return <QuadColors />;
})}
<div ref={footRef} />
</div>
</>
);
}```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该给SETSTATE提供更新功能,而不是更新的值本身(观察者回调函数中封闭值的原因)。尝试下一步:
因此,每当您启动SetState函数时 - 您拥有状态的最新值。
You should give an update function to setState, not an updated value itself (cause of enclosured value within observer callback function). Try to do next:
Thus whenever you fire setState function - you have the latest value of state.