You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Redux Toolkit的createAsyncThunk中获取当前state值

解决方案

createAsyncThunk 接收的异步处理函数支持第二个参数,是Redux Thunk提供的API对象,你可以从中解构出getState方法,调用即可拿到当前完整的store state,修改后的代码如下:

export const loginAsync = createAsyncThunk(
  "user/login",
  async (_, { getState }) => {
    try {
      // 获取state中的formLogin字段存入变量
      const userCredentials = getState().formLogin;
      const { content } = await login(userCredentials);
      localStorageHelpers.setUserToken(content.token);
      localStorageHelpers.setUserId(content.userId);
      return content.userId;
    } catch (err) {
      console.log(err)
    }
  }
);

注意事项

  • 代码中的_是占位符,用于接收你调用loginAsync时主动传入的参数,如果你调用时需要传递额外参数(比如验证码等),替换为对应参数名即可。
  • getState()返回的是整个Redux store的全量state,取值路径需要和你定义的store结构匹配,如果formLogin挂载在某个子reducer切片下,需要对应调整取值路径,比如getState().user.formLogin。

内容的提问来源于stack exchange,提问作者Erwin Ramadhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:57:00