React Native-如何更新帖子的FlatList(新喜欢,...) [英] React Native - how to update FlatList of posts (new likes, ...)
问题描述
我正在开发一个帖子列表,该列表嵌套在一个具有刷新功能的平面列表中,并且每个帖子(呈现在Card中)都具有上载该帖子的用户的头像.另外,用户可以更改其头像,因此我需要使用新的用户头像更新帖子FlatList.
I am developing a list of posts, which is nested in a flatlist that has a pull to refresh implemented, and each post (rendered in a Card) has the avatar of the user who uploaded it. Also, it is possible for a user to change its avatar, so I need to update the posts FlatList with the new user avatar.
我已经阅读了有关ExtraData道具的内容,但不适用于我的情况.
I have read something about the ExtraData prop but doesn't work in my case.
// Posts Screen
export default function Posts(props) {
const {
userData: {
username,
avatar
}
} = props;
const [data, setData] = useState([]); // [{ avatar, username, photoUri, likes }, ...]
let previousAvatar = useRef(avatar).current;
// ... Fetch the data
// This is the wrong(?) stuff I am doing to update the FlatList
useEffect(() => {
if (previousAvatar !== avatar) {
// For each post, change the avatar
setPosts(
posts.map((post) => ({
...post,
avatar: avatar,
}))
);
// Save the new avatar
previousAvatar = avatar;
}
}, [ownerData]);
return (<FlatList data={data} renderIt... />)
}
我在做什么
当我检测到用户已更改其头像时,我将修改传递给FlatList的数据,从而更改头像uri.我认为这很糟糕,因为列表中可能有10万个帖子...
What I am doing
When I detect that the user has change its avatar, I modify the data which is passed to the FlatList, changing the avatar uri. I think this is bad, as there can be 100K posts in the list...
另外,当有新的点赞,新的用户名时,我需要更新单位列表...所以我认为这不可行
Also, I need to update the flatlist when new likes, new username, ... So I think this is not viable
// Posts Screen
export default function Posts(props) {
const {
userData
} = props;
...
return <FlatList data={data} extraData={userData} ... />
}
在文档中说通过将多余的数据传递给FlatList,我们确保状态改变时FlatList本身将重新呈现."但是对我来说,这是行不通的,因为通过道具接收到了userData.
In the documentation says "By passing extraData to FlatList we make sure FlatList itself will re-render when the state changes.", but for me, this doesn't work, as userData is received via props.
有什么想法吗?谢谢.
推荐答案
flatList将呈现数据,而不是extraData.尝试将extraData设置为布尔值,并在每次需要更新列表时反转布尔值.
flatList will render the data and not the extraData. try setting the extraData to a boolean and reverse the boolean value everytime you need to update the list.
这篇关于React Native-如何更新帖子的FlatList(新喜欢,...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!