嘿,伙计们,我正试图从我的数据库中删除一篇文章,但我有问题,让这个按钮工作。我将整个函数移到我的feed文件中,创建了一个不同的函数,但仍然无法工作。我真的很感谢你的帮助。
…All the imports
function DeletePostBtn ({ postId }){
const navigate = useNavigate;`
const { _id } = useParams();`
const [deletePost] = useMutation(REMOVE_POST, {
variables: {id: _id },
onCompleted: () => navigate('/'),
refetchQueries: [{ query: QUERY_POSTS }],
});
// remove handler
const removeHandler = async (event) => {
event.preventDefault();
try {
await deletePost({ variables: {_id} });
} catch (e) {
console.error(e);
}
};
return (
<Button onClick={() => {
removeHandler();
alert('clicked');
}}>
<Trash/>
</Button>
);
}
export default DeletePostBtn;我在我的饲料页上叫它
const Feed = ({ posts }) => {
return (
<div className="feed container gx-12">
<div className="feedWrapper row">
<AddPost />
{posts &&
posts.map((post) => (
<Card key={post._id}>
<Card.Header>
<Row>
<Col xs={1}>
<div className="">
<Card.Img
src={Bot}
className="rounded-circle"
style={{ width: '50px' }}
/>
</div>
</Col>
<Col>
<Link
to={`/profile/${post.username}`}
style={{ fontWeight: 750 }}
className="text-start"
>
u/{post.username}
</Link>
</Col>
<Col className="text-end">
<Dropdown>
<Dropdown.Toggle
variant="text-dark"
id="dropdown-basic"
size="lg"
bsPrefix
className="dropdown"
>
<ThreeDots />
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1">
<Stack direction="horizontal">
<DeletePost />
DELETE
</Stack>
</Dropdown.Item>
<Dropdown.Item href="#/action-2">EDIT</Dropdown.Item>
<Dropdown.Item href="#/action-3">PROFILE</Dropdown.Item>
<Dropdown.Item href="#/action-3">
SUBCODEIT
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Col>
</Row>
</Card.Header>
<Card.Title>{post.enteredTitle}</Card.Title>
<Card.Body>
<Card.Text>{post.enteredText}</Card.Text>
</Card.Body>
<Card.Footer className="cardFooter">
<div>
Comments: {post.commentCount} || Click to{' '}
{post.commentCount ? 'Add' : 'Start'} comments.
</div>
<div>{post.createdAt}</div>
</Card.Footer>
</Card>
))}
;
</div>
</div>
);
};发布于 2022-11-17 00:09:11
更改组件以使用postId参数而不是useParams()
function DeletePostBtn ({ postId }){
const navigate = useNavigate;`
const [deletePost] = useMutation(REMOVE_POST, {
variables: {id: postId },
onCompleted: () => navigate('/'),
refetchQueries: [{ query: QUERY_POSTS }],
});
…
}然后将postId传递给.map()中的组件
<DeletePost postId={post._id}/>https://stackoverflow.com/questions/74440151
复制相似问题