如何使用 Redux Toolkit 中的 RTK 查询发送文件?

问题描述

我正在尝试使用 RTK 查询更改将文件上传到 API。这是我的突变代码

    addBanner: builder.mutation({
          query(body) {
            return {
              url: `/api/banners`,method: 'POST',body,}
          },})

这是我生成请求数据的方法

    const [addBanner,{ isBannerLoading }] = useAddBannerMutation();
    const new_banner = new FormData();    
    new_banner.append("file",my_file);
    new_banner.append("type",my_type);
    new_banner.append("title",my_title);
    addBanner(new_banner).unwrap().then( () => ... 

但我收到一个错误

A non-serializable value was detected in the state,in the path: `api.mutations.L-Mje7bYDfyNCC4NcxFD3.originalArgs.file`...

我知道我可以完全通过中间件禁用不可序列化检查,但我认为这不是使用 Redux Toolkit 和 RTK 的合适方式。没有文件一切正常。有没有正确的RTK上传文件方法

解决方法

编辑:@reduxjs/toolkit 1.6.1 已修复此问题 - 请更新您的软件包


我刚刚为此打开了一个问题:https://github.com/reduxjs/redux-toolkit/issues/1239 - 感谢您提出!

现在,您可能必须禁用该检查(您可以对状态中的某个路径执行此操作,同时使用 ignoredPath 选项保留其他路径)。