我正在创建一个reviewsection,我有一个包含2个现有评论的数组。当用户写评论并按下post按钮时,post会通过解构添加到数组中。当我对数组执行console.log()
操作时,我看到新数据正在插入,但我的flatList没有更新,仍然只显示我之前存在的2个评论。
我发现我可以通过在平面列表中使用extraData={Reviews}来解决这个问题。但是这仍然不起作用,我做错了什么?
初始阵列:
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",
},
];
按下按钮时调用的重构函数:
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);
};
我的平面列表:
<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>
)}
/>
1条答案
按热度按时间hi3rlvi21#
当需要更改数据以导致组件中的重新呈现时,请使用状态。
使用useState钩子定义和设置状态。
See more about state in the docs.