与这个异步thunk混淆

发布于 2025-02-12 14:03:35 字数 536 浏览 1 评论 0原文

export const loginSuccess = createAsyncThunk(
  "auth/loginSuccess",
  async (user: User) => {
    const res = await api
      .post(
        "/auth/loginSuccess",
        { user },
        {
          withCredentials: true,
        }
      )
      .then((res: any) => {
        setAxiosToken(res.data.token);
        saveToken(res.data.token);
        return { ...res.data.data, token: res.data.token };
      });

    return res;
  }
);


最后有2个返回语句,因此我对满足的还原器将获得哪个返回值感到困惑。该代码是由其他人撰写的,这就是为什么我想理解它。

export const loginSuccess = createAsyncThunk(
  "auth/loginSuccess",
  async (user: User) => {
    const res = await api
      .post(
        "/auth/loginSuccess",
        { user },
        {
          withCredentials: true,
        }
      )
      .then((res: any) => {
        setAxiosToken(res.data.token);
        saveToken(res.data.token);
        return { ...res.data.data, token: res.data.token };
      });

    return res;
  }
);


There are 2 return statements at the end so I am confused about which return value the fulfilled reducer will get. The code is written by someone else that's why I want to understand it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

愁杀 2025-02-19 14:03:36

第二个返回语句是将从您的功能返回的语句。

第一个实际上是从然后从函数返回的承诺axios返回的函数。

通过在thunk函数中使用res变量的相同名称以及传递给然后函数的响应变量,这使它有些混乱。

但是,您将收到的是代码行中生成的对象:

{ ...res.data.data, token: res.data.token }

其中res.data.data被扩散到新对象中,res.data.token is分配给该对象的令牌属性。

The second return statement is the one which will return from your function.

The first is actually returning from the then function of the promise that axios returns.

This is made a little bit confusing by using the same name for the res variable in the thunk function, and for the response variable that is passed to the then function.

But what you will receive back is the object generated in this line of code:

{ ...res.data.data, token: res.data.token }

Where res.data.data is spread into a new object, and res.data.token is assigned to the token property of that object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文