异步更改redux状态

cig3rfwq  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(167)

我使用redux工具包,初始状态如下:

initialState: {
  details: {
    id: "",
    base64: "",
  },
},

我想在初始状态中获取一个base64图像,无论用户何时登录。我决定在axios中执行以下操作:

axios.post(`${process.env.REACT_APP_API_URL_API_LOGIN}`, {
  softWareOrUser: false,
  userName: userName,
  password: password,
})
  .then((r) => {
    if (r.data.resCode === 1) {
      dispatch(setDetails({ ...details, id: r.data.Data.Id.toString() }));
      ImageFetchingHandler(r.data);
    }
  })
  .then((d) => {
    navigate({ pathname: "/main" });
  })
  .catch(() => {
    alert("user name or password is incorrect");
  });

这是我如何获取图像base64:

const { details } = useSelector((state) => state.axiosdetails);
const ImageFetchingHandler = ({ token }) => {
  axios({
    method: "post",
    url: `${process.env.REACT_APP_API_URL_API_FETCH_IMAGE}`,
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      "DotNet-Timeout": 30000,
    },
    data: JSON.stringify({
      id: details.id,
    }),
  })
    .then((d) => {
      Cookies.set("userImage", JSON.stringify(d.data), {
        path: "/",
        expires: 3,
        sameSite: "strict",
        secure: window.top.location.protocol === "https:",
      });
    });
};

我遇到了一个问题,ImageFetchingHandlerid值作为空字符串发送,尽管redux developer tools显示了实际的id值。
Redux developer tools shot
有什么问题吗?
有什么办法解决吗?

xqkwcwgp

xqkwcwgp1#

看起来r.data对象已经具有了您需要的所有细节,特别是它具有r.data.Data.Id属性,您正在将id状态设置为该属性,稍后您将立即尝试在ImageFetchingHandler函数中访问该属性。

dispatch(setDetails({ ...details, id: r.data.Data.Id.toString() }));
ImageFetchingHandler(r.data); // <-- id is in the data

除了访问ImageFetchingHandler中的data.token之外,您还可以访问data.Data.Id以获取有效负载的id值。

const ImageFetchingHandler = ({ Data: { Id: id }, token }) => {
  axios({
    method: "post",
    url: `${process.env.REACT_APP_API_URL_API_FETCH_IMAGE}`,
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      "DotNet-Timeout": 30000,
    },
    data: JSON.stringify({ id }),
  })
    .then((d) => {
      Cookies.set("userImage", JSON.stringify(d.data), {
        path: "/",
        expires: 3,
        sameSite: "strict",
        secure: window.top.location.protocol === "https:",
      });
    });
};
v1uwarro

v1uwarro2#

details创建一个副作用,检查details.id是否存在。如果存在,则运行fetch函数。

useEffect(() => {
  if(details.id) {
    // call API here
  }
}, [details])

一旦组件呈现,详细信息字段在该时间点为空。details字段异步获取其实际值。

相关问题