function Design() {
const[designRows,setDesignRows]=useState([])
const design = useSelector((state) => state.design)
useEffect(()=>{
for (var i = 0; i < design; i ) {
setDesignRows([...designRows, <DesignRow key={i} />])
}
},[designRows])
return (
<>
<section className='mt-5 p-3 w-2/5'>
<div className=' text-center p-2 h-20 bg-gray-200 font-bold text-lg'>Game Design</div>
<div className='border p-3 mt-6 text-gray-500 font-medium text-sm'>
{designRows.map(data=>(
<>{data}</>
))}
</div>
</section>
</>
)
}
export default Design
above program is rendering infinite DesignRow components, I want to render "design" no of components.[design is my global/redux state]
CodePudding user response:
The source of your problem is you are watching for "designRows" state and updating in the same useEffect, that what is causing it to loop infinitely. I don't understand exactly what do you want to achieve, but I guess you want to render n number of components where n is the length of your design Array, if so you can try :
const[designRows,setDesignRows]=useState([])
const design = useSelector((state) => state.design)
return (
<>
<section className='mt-5 p-3 w-2/5'>
<div className=' text-center p-2 h-20 bg-gray-200 font-bold text-lg'>Game Design</div>
<div className='border p-3 mt-6 text-gray-500 font-medium text-sm'>
{design.length > 0 && design.map((d,key) => (<DesignRow key={key} />) )}
</div>
</section>
</>
)
}
export default Design```
CodePudding user response:
Your code snippet will cause an infinite rendering of component because you are updating the value of designRows in useEffect
and at the same time added it in the dependencies in useEffect
. To fix this either remove the updating of designRows
in useEffect or remove the designRows
from dependency array in useEffect
.
CodePudding user response:
You need to change it to this:
useEffect(()=>{
for (var i = 0; i < design; i ) {
setDesignRows([...designRows, <DesignRow key={i} />])
}
},[design])
The second argument is the dependencies - when updated, it triggers the effect.