错误:“ index.js:1警告:无法在已卸载的组件上执行React状态更新。这是无操作,但表示您的应用程序中存在内存泄漏。要修复,取消所有订阅并Home(由Context.Consumer创建)中的useEffect清理功能中的异步任务”
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useMutation } from "@apollo/``react-hooks";
import gql from "graphql-tag";
import { Button, Icon, Label } from "semantic-ui-react";
const LikeButton = ({ user, post: { id, likeCount, likes } }) => {
const [liked, setLiked] = useState(false);
useEffect(() => {
if (user && likes.find(like => like.username === user.username)) {
setLiked(true);
} else {
setLiked(false);
}
}, [likes, user]);
const [likePost] = useMutation(LIKE_POST_MUTATION, {
variables: { postId: id },
update(proxy, result) {
likes = result.data.likePost.likes;
}
});
const likeButton = user ? (
liked ? (
<Button color="red">
<Icon name="heart" />
</Button>
) : (
<Button basic color="red">
<Icon name="heart" />
</Button>
)
) : (
<Button as={Link} to="/login" basic color="red">
<Icon name="heart" />
</Button>
);
return (
<Button as="div" labelPosition="right" onClick={user ? likePost : null}>
{likeButton}
<Label basic color="red" pointing="left">
{likeCount}
</Label>
</Button>
);
};
const LIKE_POST_MUTATION = gql`
mutation likePost($postId: ID!) {
likePost(postId: $postId) {
id
likeCount
likes {
id
username
}
}
}
`;
export default LikeButton;
当我不喜欢帖子时(例如按钮和计数立即更新),效果很好,但是当我喜欢帖子时,必须刷新页面以更新喜欢计数