I'm creating an array of indexes
in which I'm appending values(this will later be used in a map function).
let indexes = [];
export default function SortTiles() {
let num = info.num_tiles;
for (let i = 10; i < num 10; i ) {
indexes = [...indexes, i];
}
console.log(indexes);
console.log("UWU")
return(
<div id={"sort-tiles"}>
{/*{indexes.map(makeTiles)}*/}
</div>
)
}
But when I'm trying to console.log my array this is the output I'm getting: The output image The output is being printed twice and the numbers in the array are also duplicated.
CodePudding user response:
Not sure what are you trying to achieve but this is not the proper way to handle arrays or any data in react component.
Try this may be this will help you or might fix your problem.
import {useState, useEffect} from 'react';
export default function SortTiles() {
const [indexes, setIndexes] = useState([]);
useEffect(() => {
let num = 20;
let indexArr = []
for (let i = 10; i < num 10; i ) {
indexArr = [...indexArr, i];
}
setIndexes(indexArr);
}, [])
return(
<div id={"sort-tiles"}>
{indexes.map((ind) => (<div>{ind}</div>))}
</div>
)
}
CodePudding user response:
The array is printed twice most likely because you are in strict mode, which double renders components to help catch bugs.
Lucky for you, it helped you catch one! The values are duplicated because the indexes
variable is declared outside the function. Since you never reset it to an empty value, every re-render will just continue adding indexes. Try initializing it inside the function.