简体   繁体   English

如何在 react-Native 中的平面列表中使用 extraData

[英]How to use extraData in a flatlist in react-Native

I'm making a reviewsection, I have an array with 2 existing reviews.我正在制作评论部分,我有一个包含 2 条现有评论的数组。 When the user writes a review and pressed the post button the post gets added into the array using destructuring.当用户撰写评论并按下发布按钮时,帖子将使用解构添加到数组中。 This works when I do a console.log() of the array I see the new data being inserted but my flatList is not updated and still only shows my 2 previously existing reviews.这在我执行数组的console.log()时有效,我看到正在插入新数据,但我的 flatList 没有更新,仍然只显示我以前存在的 2 个评论。

I found out I can solve this by using extraData={Reviews} in my flatlist.我发现我可以通过在平面列表中使用 extraData={Reviews} 来解决这个问题。 But this still does not work, what am I doing wrong?但这仍然不起作用,我做错了什么?

initial array:初始数组:

let Reviews = [
    {
      title: "I love F1",
      name: "Tibo Mertens",
      review:
        "This car may have a legendary driver on their team, but unfortunately, their car doesn't live up to his skills",
    },
    {
      title: "F1 is awesome",
      name: "Quintt Adam",
      review:
        "This car is extremely middle of the pack when it comes to the best car on the grid of 2022",
    },
  ];

Destructuring function that gets called when the button is pressed:解构按下按钮时调用的 function:

const addReview = (title, name, review) => {
    const newReview = { title: title, name: name, review: review };

    const modifiedObj = {
      title: newReview.title,
      name: newReview.name,
      review: newReview.review,
    };

    Reviews = [modifiedObj, ...Reviews];

    console.log(Reviews);
  };

My flatList:我的公寓清单:

<FlatList
          data={Reviews}
          extraData={Reviews}
          renderItem={({ item }) => (
            <View style={styles.listContainer}>
              <View style={styles.reviewContainer}>
                <Text style={styles.reviewTitle}>{item.title}</Text>
                <Text style={styles.review}>{item.review}</Text>
                <Text style={styles.reviewName}>- {item.name}</Text>
              </View>
            </View>
          )}
        />

Use state when you need a change in data to cause a re-render in a component.当您需要更改数据以导致在组件中重新呈现时,请使用 state。 Instead of代替

  let Reviews = [
    ...
  ]
  ...
  Reviews = // etc

Define and set your state with the useState hook.使用 useState 挂钩定义并设置您的 state。

  const existingReviews = [
    // your existing reviews
  ]; 
  const [reviews, setReviews] = useState(existingReviews);

  // to set
  setReviews(modifiedObj);

See more about state in the docs.在文档中查看有关 state 的更多信息。

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

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