I am working on a react native app, where I am using FlatList
for some purpose. I have a list of items displayed through the FlatList
. That FlatList returns a component that I have made the finally displays the items.
const [allAmen , setAllAmen] = useState({});
let arr = [];
const test = (uName) => {
setAllAmen({...allAmen , "name" : uName })
}
arr.push(allAmen);
console.log(arr);
<FlatList
data={amens}
keyExtractor={(amen) => amen.id}
renderItem={({item}) => {
<TouchableOpacity
onPress={() => {
test(item.name)
}}
>
<Text>{item.name}</Text>
</TouchableOpacity>
}}
/>
When I run this and press on one of the items of the list, it set the object in allAmen and pushes in arr. But if I press another item, it makes a new array and gives the result. S0 for every item of the flatlist a new state object and the array is created and the result is pushed in for a different array for each item. So if I have the following:
Flatlist ->
Candy Bar White Chocolate Bar Red Velvet
and I press on first I get -> [{"name": Candy Bar}]
but then if I press on White Chocolate Bar it gives, [{"name": White Chocolate Bar }]
and same for Red Velvet.
What I want is if I press first i get -> [{"name": Candy Bar}] then if I press second and after that third-> [{"name": Candy Bar}, {"name": White Chocolate Bar}, { "name": Red Velvet}]
.
But it is running individually for every list. Can someone help me on how to do this? I am fairly new to react native and javascript and running it to a lot of doubts. Tried to find it on StackOverflow and internet but could not get anything relevant.
const newValue = {"name" : uName};
setAllAmen(prevArray => [...prevArray, newValue])
See more explanations. https://stackoverflow.com/a/58556049/905494 https://stackoverflow.com/a/54677026/905494
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.