React.Js如何在表单提交时重定向



每个人。

所以我有一个应用程序,用户可以在其中创建帖子,如果你是这个帖子的所有者,你可以点击删除按钮,它会显示一个模态,你可以删除帖子。

我可以删除帖子,但现在我正试图将用户重定向回主页或任何其他页面,但它不起作用。

我试过使用history.push,但它不可用,window.location.replace("/")不起作用,我甚至试过使用这个

const navigate = useNavigate();

并在表格中提交

navigate("/");

这根本不起作用,相反发生的是:

  • DELETE请求被发送
  • 帖子从数据库中删除
  • 页面会重新加载并且不会重定向用户
  • 控制台抛出获取错误

用户只有在手动切换页面后才能看到帖子被删除,这是我不希望的,我希望用户在按下"删除帖子"按钮后自动重定向。

这是我的包.json

"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.11.41",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"typescript": "^4.7.4",
"web-vitals": "^2.1.4"
},

这是我在Post 上提交和删除表格的代码

const Post_page = () => {
const auth = useContext(context_auth);

const { isLoading, error, sendRequest, clearError } = useHttpRequest();
const [showModal, setShowModal] = useState(false);
const userID = useParams().id;
const [title, setTitle] = useState();
const [postID, setPostId] = useState();
const [description, setDescription] = useState();
const [creator_name, setCreatorName] = useState();
const [creationTime, setCreationTime] = useState('');
const openModal = (event: any) =>  {
setShowModal(true);
}
const closeModal = (event: any) =>  {
setShowModal(false);
}
const onSubmit = async (event: any) => {
event.preventDefault();
console.log("aaaaaaaaaaaaa");
try {
const url: string = `http://localhost:8000/api/posts/${postID}`;
await sendRequest(url, 'DELETE');
window.location.replace("/");
closeModal(event);
} catch (err: any) {
console.log(err.message)
}



}
useEffect(() => {
const fetchPosts = async () => {
try {
const url: string = `http://localhost:8000/api/posts/${userID}`;
const responseData = await sendRequest(url);
console.log(responseData.post);
const data = responseData.post;
setTitle(data.title);
setDescription(data.description);
setPostId(data.id);
const timeOfCreation = new Date(data.createdAt).toDateString();
setCreationTime(timeOfCreation);
setCreatorName(data.creator_name);
} catch (err) { }}
fetchPosts();
}, [sendRequest]);

return (
<>
{isLoading &&
<h1>Loading ...</h1>
}
{ !isLoading && showModal &&  auth.isLoggedIn &&   
<Modal title='Delete post' show={showModal} onCancel={closeModal}>
<>
<Form onSubmit={onSubmit} classname='modal_content_height_auto'>
<p className='post_description'>Do you want to delete this post ?</p>
<Button 
classname='button_submit' 
classname_enabled='button_submit_enabled' 
classname_disabled='button_submit_disabled' 
type='submit'
label='Delete' 

/>
</Form>
</>

</Modal>
}
{ !isLoading &&

<here is the post stuff, hidden as its not important>
<Comments />
</div>
}
</>
)
}
export default Post_page

编辑:发布删除后的后端代码

这是我的路线

route.delete('/:postID', deletePost)

这是deletePost处理程序

export const deletePost = async (req: Request, res: Response, next: NextFunction) => {
const postID = req.params.postID;
let post: any;
try {
post = await POST.findById(postID).populate('creator_id');
} catch (err: any) {
console.log(err.message)
const error = {
message: "Couldn't delete POST !",
code: 500
};

return next(error);
}
if(!post){
const error = {
message: "Post doesn't exist, so it could not be deleted !",
code: 404
};

return next(error);
}
try{
await post.remove();
post.creator.posts.pull(post);
await post.creator.save();

}catch(err){
const error = {
message: "Couldn't delete POST from DATABASE!",
code: 500
};

return next(error);
}
res.status(200).json({message: "Post deleted !"});
}

编辑:为帖子和用户添加了架构这是我的Post架构,它也连接到用户架构

import mongoose from "mongoose";
const Schema = mongoose.Schema;
const post_Schema = new Schema({
title: { type: String, required: true, },
description: { type: String, required: true, },
imageURL: { type: String },
creator_id: { type: mongoose.Types.ObjectId, required: true, ref: 'User'  }, //relation bewtean post and user
creator_name: { type: String, required: true, ref: 'User'  }, //relation bewtean post and user
},
{ timestamps: true }
);
export const POST: mongoose.Model<any> = mongoose.model("Post", post_Schema);

这是我的用户模式

import mongoose from "mongoose";
import mongooseUniqueValidator from "mongoose-unique-validator";
const Schema = mongoose.Schema;
const validator = mongooseUniqueValidator;
const user_Schema = new Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, minlength: 3 },
user_image: { type: String },
posts: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Post'  }], //relation bewtean post and user
},{ timestamps: true }
);
user_Schema.plugin(validator);

export const USER: mongoose.Model<any> = mongoose.model("User", user_Schema);

根据您发布的内容,您在删除帖子时不重定向的原因是后端阻止了这种情况的发生。

  1. 要在用户删除帖子后重定向用户,如果您使用的是React router dom版本6,则需要使用useNavigate()。因为useHistory和已被useNavigate取代,因此如果用户删除了某些内容,您将如何重定向用户
const navigate = useNavigate();
const onSubmit = async (event: any) => {
event.preventDefault();
try {
const url: string = `http://localhost:8000/api/posts/${postID}`;
await sendRequest(url, 'DELETE');
closeModal(event);
navigate(`/`);
} catch (err: any) {}
}
  1. 你的帖子没有重定向的原因是,当你发送DELETE请求时,后端会发回一个错误,但在错误发生之前,帖子会从数据库中删除,并在第二次尝试中发生。。挡块。错误发生在这里->
post.creator.posts.pull(post);  //THIS IS WERE THE ERROR HAPPENS

发生此错误的原因是您正在Post Schema中搜索创建者,但Post Schema没有creator,因此它惊慌失措并抛出错误,相反,它有createator_idcreator_name。因此,如果您正在按id 搜索用户,则应该像这样替换它

post.creator_id.posts.pull(post);

因此,后端的代码应该是这样的(除了post.creator_id.posts.pull(post)

export const deletePost = async (req: Request, res: Response, next: NextFunction) => {
const postID = req.params.postID;
let post: any;
try {
post = await POST.findById(postID).populate('creator_id');
} catch (err: any) {
console.log(err.message)
const error = {
message: "Couldn't delete POST !",
code: 500
};
return next(error);
}
if(!post){
const error = {
message: "Post doesn't exist, so it could not be deleted !",
code: 404
};
return next(error);
}
try{
await post.remove();
post.creator_id.posts.pull(post);
await post.creator_id.save();

}catch(err){
const error = {
message: "Couldn't delete POST from DATABASE!",
code: 500
};

return next(error);
}
res.status(200).json({message: "Post deleted !"});
}

您必须仅使用Navigate,因为您使用的是react路由器v6

const Post_page = () => {
const auth = useContext(context_auth);
const navigate=useNavigate();
const { isLoading, error, sendRequest, clearError } = useHttpRequest();
const [showModal, setShowModal] = useState(false);
const userID = useParams().id;
const [title, setTitle] = useState();
const [postID, setPostId] = useState();
const [description, setDescription] = useState();
const [creator_name, setCreatorName] = useState();
const [creationTime, setCreationTime] = useState('');
const openModal = () =>  {
setShowModal(true);
}
const closeModal = () =>  {
setShowModal(false);
}
const onSubmit = async (event: any) => {
event.preventDefault();
console.log("aaaaaaaaaaaaa");
try {
const url: string = `http://localhost:8000/api/posts/${postID}`;
await sendRequest(url, 'DELETE');
//window.location.replace("/");
navigate("/");
closeModal();
} catch (err: any) {
console.log(err.message)
}



}
useEffect(() => {
const fetchPosts = async () => {
try {
const url: string = `http://localhost:8000/api/posts/${userID}`;
const responseData = await sendRequest(url);
console.log(responseData.post);
const data = responseData.post;
setTitle(data.title);
setDescription(data.description);
setPostId(data.id);
const timeOfCreation = new Date(data.createdAt).toDateString();
setCreationTime(timeOfCreation);
setCreatorName(data.creator_name);
} catch (err) { }}
fetchPosts();
}, [sendRequest]);

return (
<>
{isLoading &&
<h1>Loading ...</h1>
}
{ !isLoading && showModal &&  auth.isLoggedIn &&   
<Modal title='Delete post' show={showModal} onCancel={closeModal}>
<>
<Form onSubmit={onSubmit} classname='modal_content_height_auto'>
<p className='post_description'>Do you want to delete this post ?</p>
<Button 
classname='button_submit' 
classname_enabled='button_submit_enabled' 
classname_disabled='button_submit_disabled' 
type='submit'
label='Delete' 

/>
</Form>
</>

</Modal>
}
{ !isLoading &&

<here is the post stuff, hidden as its not important>
<Comments />
</div>
}
</>
)
}
export default Post_page

如果从删除请求中获得获取错误,则意味着window.location.replacecloseModal函数都不会被调用,因为catch块在错误之后立即执行。确保您从API调用中得到了正确的响应。

最新更新