繁体   English   中英

React Native:如何使用 Hooks 在列表顶部添加新元素并使用 map() 进行渲染?

[英]React Native: How to add new element at the top of the list using Hooks and render using map()?

我试图添加一个新数据并将其放在我从 API 获得的数组的顶部。 问题是新数据仍然在数组的末尾,即使 console.log 输出了所有数据,它也只渲染新数据而不是全部。 我知道问题不在于样式,因为如果我不添加新数据,它能够正确呈现。

这就是我添加新数据的方式:

    fetch()
    **********
    .then((result) => {
    setListTab(result);
    setListTab(listTab => [listTab, {id: 18, name: "All", ...listTab}]);
    console.log(listTab);


    <ScrollView 
        showsHorizontalScrollIndicator={false} 
        horizontal={true}>
        {listTab.map(item => (
            <TouchableOpacity key={item.id} 
                activeOpacity={1}> 
                <Text>{item.name}</Text>
            </TouchableOpacity>
        ))}

首先,你不应该使用ScrollView来实现Lists,请使用FlatList。

您的逻辑(根据您发布的代码)不正确。 要将新对象添加到数组的第一个,您可以很好地使用扩展运算符。

示例代码: https ://jsfiddle.net/rzhybtdj/

let friendsList = [{"id":343,"name":"Satheesh"}, {"id":342,"name":"Kavitha"}];
// something happened and I have a new friend now.
// To add it to the firendsList array I do this
const newFriend = {"id":341,"name":"Yuvan"};
friendsList = [newFriend, ...friendsList];

现在来看看你的代码,以及它应该如何制作你想要的东西。

fetch()
.then((result) => {
const newList = [...result, ...listTab]; //considering result being an array, if an object then [result, ...listTab]
setListTab(newList);
console.log(newList);

让我知道这是否适合您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM