在反应中调用调度函数

To call dispatch function in react

我不知道在哪里调用 dispatch(setAlert()) 函数。我在 axios.patch 请求后想要它,但目前它不起作用

  let url = `.....................`;
  const handleSubmit = (e) => {
    e.preventDefault(); 
    axios
      .patch(url, form_data, {
        headers: {
          Authorization: `JWT ${localStorage.getItem("access")}`,
          "content-type": "application/json",
        },
      })
      dispatch(setAlert('Data changed successfully.', 'success'));
      .then(() => axios.get(url))
      .then((res) => {
        console.log(res.data);
        updateFormData({
          ...formData
        })
      })
      .catch((err) => console.log(err));
    };  

您可以使用 async / wait 然后等到补丁调用完成。

  const handleSubmit = async (e) => {
    e.preventDefault(); 
    await axios
      .patch(url, form_data, {
        headers: {
          Authorization: `JWT ${localStorage.getItem("access")}`,
          "content-type": "application/json",
        },
      })
      dispatch(setAlert('Data changed successfully.', 'success'));
      .then(() => axios.get(url))
      .then((res) => {
        console.log(res.data);
        updateFormData({
          ...formData
        })
      })
      .catch((err) => console.log(err));
    };  

patch 调用之后立即在 then 内添加 dispatch 调用:

const handleSubmit = (e) => {
    e.preventDefault(); 
    axios
      .patch(url, form_data, {
        headers: {
          Authorization: `JWT ${localStorage.getItem("access")}`,
          "content-type": "application/json",
        },
      })
      .then(() => {
         dispatch(setAlert('Data changed successfully.', 'success'));
         axios.get(url));
       }
      .then((res) => {
        console.log(res.data);
        updateFormData({
          ...formData
        })
      })
      .catch((err) => console.log(err));
    };  

编辑: 确保在 class 组件的情况下连接组件或在功能组件的情况下导入 useDispatch 挂钩,例如:

import { useDispatch } from 'react-redux'

function SomeComponent() {
    const dispatch = useDispatch();
    ...
    // your code place

}