[英]Create a single state array for all items of flatlist. (React Native)
I am working on a react native app, where I am using FlatList
for some purpose.我正在开发一个反应原生应用程序,我出于某种目的使用
FlatList
。 I have a list of items displayed through the FlatList
.我有一个通过
FlatList
显示的项目列表。 That FlatList returns a component that I have made the finally displays the items.该 FlatList 返回一个组件,我最终显示了这些项目。
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.当我运行它并按下列表中的一项时,它会在 allAmen 中设置 object 并推入 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.
S0 为 flatlist 的每个项目创建一个新的 state object 并创建数组并将结果推入每个项目的不同数组。 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.我先按下我得到 ->
[{"name": Candy Bar}]
但是如果我按下 White Chocolate Bar 它会给出[{"name": White Chocolate Bar }]
和 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}]
.我想要的是如果我先按我得到 -> [{"name": Candy Bar}] 然后如果我按第二个然后按第三个->
[{"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.
我对本机和 javascript 做出反应并运行它遇到很多疑问是相当新的。 Tried to find it on StackOverflow and internet but could not get anything relevant.
试图在 StackOverflow 和互联网上找到它,但找不到任何相关信息。
const newValue = {"name" : uName};
setAllAmen(prevArray => [...prevArray, newValue])
See more explanations.查看更多解释。 https://stackoverflow.com/a/58556049/905494 https://stackoverflow.com/a/54677026/905494
https://stackoverflow.com/a/58556049/905494 https://stackoverflow.com/a/54677026/905494
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.