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

在React Native Expo中如何在Redux里使用SecureStore存储API返回的token

React Native Expo Redux 集成 SecureStore 存储用户Token实现

以下是在Redux异步逻辑中调用Expo SecureStore完成用户Token存储、读取的可运行实现代码:

// 存储Token:OTP验证通过后写入SecureStore
export const verifyOTP = (formValues, actions) => {
  return async (dispatch) => {
    dispatch(startSubmitting());
    const url = `/validate-otp`;

    var formdata = new FormData();

    formdata.append("mobile", formValues.mobile);
    formdata.append("otp", formValues.otp);
    const response = await api.post(url, formdata);
    

    dispatch({
      type: "VERIFY_OTP",
      payload: response,
    });
    dispatch(stopSubmitting());
    await SecureStore.setItemAsync("userToken", response.data.access_token);
  };
};

// 读取Token:校验用户登录态时从SecureStore取出
export const checkUser = () => {
  return async (dispatch) => {
    const token = await SecureStore.getItemAsync("userToken");
    const url = `/me`;
    const response = await api
      .post(url, { token })
      .then((res) => {
        return res;
      })
      .catch((error) => {
        return error.response;
      });

    dispatch({
      type: "CHECK_USER",
      payload: response,
    });
  };
};

可选优化点

  • 可在SecureStore.setItemAsync调用处增加异常捕获,避免存储失败时无兜底逻辑
  • 读取Token后可先判空,无Token时可直接触发未登录的Redux状态更新,无需调用后端接口
  • 统一封装SecureStore的读写方法,便于后续全局统一配置存储参数(如加密级别、有效期等)

内容的提问来源于stack exchange,提问作者afshana zaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:48:04