如何在每次运行的map函数中更改setstate



如何在地图功能运行时显示状态

每次我的地图功能运行时,我都想将计数增加50。

就像地图获取一个博客一样,现在的数量是50第二次计数为100,依此类推。

设置状态:

const[count,setCount]=useState(0(;

地图功能代码:

{blogs.slice(0).map((item) => {                
return <Link key={item.slug.current} href={"/blog-post/" + item.slug.current}>
<article className="ip oo ik" data-aos="fade-up" data-aos-delay={`${count}`}>
<header>
<a href={"/blog-post/" + item.slug.current}>
<span className="ic re" href="blog-post.html">
<figure className="tq ig fe o_ oq">
<Image className="tj tz su ik an o lz ci cl" src={builder.image(item.mainImage).width().url()} layout='fill' sizes="50vw" priority='true' quality={60} alt={item.Alt} />
</figure>
</span>
</a>
<h3 className="h3 ra"> <span className="c_ lz cr cf text-hover text-2xl "><a href={"/blog-post/" + item.slug.current}>{item.title}</a></span> </h3>
</header>
<a href={"/blog-post/" + item.slug.current}>
<p className="fm li sz hover:text-black dark:hover:text-white">{item.metadesc}</p>
</a>
<footer className="ip ol rv"> <span>
{/* <Image className="oj sq rl" src="/" width="40" height="40" alt="Author 01" /> */}
</span>
<div className="fk"> <span className="lr c_ lz cr cf text-hover">{item.Name}</span> <span className="lc"> - </span> <span className="lf">{item.publishedAt}</span> </div>
</footer>
</article>
</Link>

})}

使用状态将无法做到这一点,因为map函数是渲染的一部分,而更改状态会触发重新渲染,最终将进入无限循环。您可以尝试使用useRef,但不确定这是否适用于您:

const ref = useRef(0);
{blogs.slice(0).map((item) => {
// However much you want to increase it, bear in mind this will add for every element in the array
ref.current = ref.current + 50;
return (<Link key={item.slug.current} href={"/blog-post/" + item.slug.current}>
<article className="ip oo ik" data-aos="fade-up" data-aos-delay={`${count}`}>
...
);
}}

最新更新