我正在制作一个 instagram 克隆,但在我“喜欢”帖子时遇到了问题。更新后的状态导致我的所有图像消失并重新渲染,而不仅仅是我喜欢的图像(并且可能重新下载,虽然我不确定)我已经尝试使用 React.memo,shouldComponentUpdate(我知道这很愚蠢将两者混合,但我越来越绝望。非常感谢任何帮助/建议。我已尝试按流程顺序排列我的代码:
const [socialPosts, setSocialPosts] = useState([])
const [likedPosts, setLikedPosts] = useState({likedPosts: []}
<View, etc />
<FlatList
data={socialPosts}
renderItem={(item, index) => _renderItem(item, index)}
extraData={likedPosts}
keyExtractor={(item, index) => `itemsocial${item.SK}`}
refreshing={refreshing}
onRefresh={fetchRounds}
/>
</View>
const _renderItem = (item, index) => {
const userLiked = likedPosts.likedPosts.includes(item.item.SK);
return <TotalWithRender item={item} index={index} isLiked={userLiked} />;
};
const TotalWithRender = React.memo(TotalRoundItem, areEqual);
const areEqual = (prevProps, nextProps) => {
///Commented out, but this would be the code I use to trigger a refresh. It doens't work.
// return nextProps.item.SK === prevProps.item.SK
// likedPosts.likedPosts.includes(
// nextProps.item.SK
//) === likedPosts.likedPosts.includes(
// prevProps.item.SK
//)
//Returning true, but I still have a refresh.
return true;
};
我的项目,由页眉、正文和页脚组成。我正在分开,希望我能找到一种只重新渲染页脚的方法。没有运气。
const TotalRoundItem = ({ item, index, isLiked }) => {
return (
<>
<View >
<SocialItemHeader social={item} index={index} />
<SocialItemClass social={item} index={index} />
<SocialItemFooter social={item} index={index} userLiked={isLiked} />
</View>
</>
);
};
我会分享身体
class SocialItemClass extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
//Putting false as I do NOT want this to re-render
return false;
}
render() {
const social = this.props.social;
return (
<>
{social.item.ImageURI && social.item.ContentType === "image" && (
<Image
source={{
uri: `${config.cloudfrontDist}${social.item.ImageURI}`
}}
/>
)}
</>
);
}
}
以及包含“喜欢”的页脚...我只希望在喜欢帖子时重新渲染此内容
class SocialItemFooter extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// Again, keeping this false as I was hoping to prevent re-renders entirely. No luck
return false
}
render() {
const social = this.props.social;
const userLiked = this.props.userLiked;
return (
<View>
<TouchableOpacity
onPress={() => {
postLike(social.item["SK"], userLiked);
}}
>
<HeartSymbol fill={userLiked} />
</TouchableOpacity>
...other code
</View>
);
}
}
最后,我的 postLike 函数:
const postLike = async (roundSK, userLiked) => {
if (userLiked) {
const likedPostsClone = { ...likedPosts };
const itemIndex = likedPostsClone.likedPosts.indexOf(roundSK);
if (itemIndex > -1) {
likedPostsClone.likedPosts.splice(itemIndex, 1);
setLikedPosts(likedPostsClone);
}
} else {
setLikedPosts((prev) => ({
likedPosts: [...prev.likedPosts, roundSK]
}));
}
};