I am trying to display a flatList of numbers like this : (image of what the flat list would look like) To do that I did an array of objects with a numberName and a key, it's generating with a loop:
const number = 5;
let [numbers, setNumbers] = useState([]);
let nums = [];
for (let i = 0; i < number; i ) {
nums.push({ numberName: i, key: i });
console.log(nums)
}
setNumbers((numbers) => [...numbers, ...nums]);
I dont think the problem is in the loop, but react is recalling the loop without showing the component. This makes an infinite loop and I have the too Many rerender error.
Here is what console.log(nums) shows (screenshot of the console)
and here is how i am trying to render the array :
if(!fontsLoaded) {return <AppLoading />}
else {return (
<View>
<FlatList
showsHorizontalScrollIndicator={false}
horizontal={true}
data={numbers} //la data qu'on va afficher
renderItem={({ item }) => (
<Text style={styles.number}>{item.numberName}</Text>
)} //la fonction qu'il va rendre
/>
</View>
)}
Why do I have the too many rerenders error and how do I fix it ?
CodePudding user response:
let [numbers, setNumbers] = useState([]);
useEffect(()=>{
const nums = numbers.map((value,index)=> {numberName: index,key: index})
setNumbers([...numbers, ...nums])
},[])
You need to do assignment/state-related stuff inside useEffect hook.
CodePudding user response:
const number = props.numberProp;
let [numbers, setNumbers] = useState([]);
useEffect(() => {
let nums = [];
for (let i = 0; i < number 100; i ) {
nums.push({ numberName: i, key: i });
}
setNumbers((numbers) => [...numbers, ...nums]);
}, [])