アプリにデータベースリスナーがあり、ユーザーが何かを投稿するたびにデータの状態を更新します。新しい投稿を取得したら、FlatListがレンダリングするすべてのアイテムを含む配列である「posts」という状態を更新します。
問題は、状態を更新した後、(リストのフッターに)下がってから一番上に戻るまで、リストの一番上に新しい投稿が表示されないことです。
私のFlatListコードは次のとおりです。
const keyExtractor = ({id}) => id
...
const renderItem = ({ item }) => {
const {
uri,
description,
location,
width,
height,
likes,
comments,
date,
} = item;
return (
<Card
uri={uri}
description={description}
location={location}
width={width}
height={height}
likes={likes}
date={date}
/>
);
};
return (
<FlatList
data={data} // data is the post state of the parent
renderItem={renderItem}
keyExtractor={keyExtractor}
initialNumToRender={15}
windowSize={WINDOW_HEIGHT * 2}
maxToRenderPerBatch={15}
updateCellsBatchingPeriod={50}
removeClippedSubviews={false}
ListFooterComponent={
isLoading ? (
<View style={styles.footer}>
<Loading type="ios" size={18} color={colors.gray} />
</View>
) : null
}
/>
);
}
そして、これは私が投稿の状態を更新する方法です(フラットリストの親コンポーネントで)
function Posts(props) {
const [posts, setPosts] = useState([]);
useEffect(() => {
const { firebase } = props;
let postsArray = [];
// Realtime database listener
const unsuscribe = firebase
.getDatabase()
.collection("posts")
.doc(firebase.getCurrentUser().uid)
.collection("userPosts")
.orderBy("date") // Sorted by upload date
.onSnapshot((snapshot) => {
let changes = snapshot.docChanges();
changes.forEach((change) => {
if (change.type === "added") {
// Get the new post
const newPost = change.doc.data();
// Add the new post to the posts list
postsArray.unshift(newPost);
}
});
// Reversed order so that the last post is at the top of the list
setPosts(postsArray);
});
/* Pd: At the first time, this function will get all the user's posts */
return () => {
// Detach the listening agent
unsuscribe();
};
}, []);
return (
<View style={styles.container}>
<CardList data={posts} />
</View>
);
}
この問題は、新しい投稿を追加することで発生する可能性があります。
postsArray.unshift(newPost)
..
setPosts(postsArray)
の参照には影響しないようですpostsArray
。したがって、状態の更新は発生せず、再レンダリングも見られません。
代わりに、次のことを試してみてください。
setPosts([...postsArray])
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加