postSlice.js
createPost: builder.mutation({
query: ({ usersId, ...form }) => ({
url: `/createPost/user/${usersId}`,
method: "POST",
body: { form, userId: usersId },
// responseHandler: (response) => response.text(),
}),
invalidatesTags: ["User"],
})
post.jsx
const [createPost] = useCreatePostMutation();
const state = useSelector((state) => state);
const usersId = window.sessionStorage.getItem("User");
const [form, setForm] = useState({
title: "",
content: "",
});
const [message, setMessage] = useState("");
const update = (e) => {
setForm((prev) => ({
...prev,
[e.target.name]: e.target.value,
}));
};
const submit = async (e) => {
e.preventDefault();
setMessage("");
try {
if (!form.title || !form.content) {
setMessage("Please fill in all required fields.");
return;
}
let response = false;
response = await createPost(form, usersId).unwrap();
console.log(response);
if (response) {
setMessage("Post successful!");
navigate("/");
}
} catch (error) {
setMessage("Post failed. Please try again.");
}
};
使用开发工具,我可以看到表单正在正确传递,userId 在切片中返回为未定义。它出现在提交函数中,但没有被传递。不知道为什么??
您的参数未正确传递,因为 createPost 突变需要一个对象,但您将参数作为单独的值传递。您应该按如下方式修改代码:
const [createPost] = useCreatePostMutation();
const state = useSelector((state) => state);
const usersId = window.sessionStorage.getItem("User");
const [form, setForm] = useState({
title: "",
content: "",
});
const [message, setMessage] = useState("");
const update = (e) => {
setForm((prev) => ({
...prev,
[e.target.name]: e.target.value,
}));
};
const submit = async (e) => {
e.preventDefault();
setMessage("");
try {
if (!form.title || !form.content) {
setMessage("Please fill in all required fields.");
return;
}
let response = false;
response = await createPost({form, usersId}).unwrap();
console.log(response);
if (response) {
setMessage("Post successful!");
navigate("/");
}
} catch (error) {
setMessage("Post failed. Please try again.");
}
};
这应该将正确的参数传递给你的突变