我的 userId 没有从页面传递到切片,但表单是。我不知道为什么它没有正确通过

问题描述 投票:0回答:1

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 在切片中返回为未定义。它出现在提交函数中,但没有被传递。不知道为什么??

javascript reactjs parameter-passing slice
1个回答
0
投票

您的参数未正确传递,因为 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.");
    }
  };

这应该将正确的参数传递给你的突变

© www.soinside.com 2019 - 2024. All rights reserved.