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

SolidJS中使用sessionStorage临时存储表单数据失效问题求助

问题诊断与解决方案

你遇到的核心问题是sessionStorage存储逻辑的执行时机错误:

在你的代码中,sessionStorage.setItem直接写在createStore初始化之后,此时form的所有字段都是初始空字符串,所以你实际存入sessionStorage的是空值,后续自然读取不到有效内容。

正确实现步骤

1. 将存储逻辑移到表单提交函数中

只有在用户提交表单时,才把当前输入的最新form值存入sessionStorage,之后再清空表单。

修改useSendVerificationEmail.jsx的代码:

import { createStore } from "solid-js/store";

export function useSendVerificationEmail() {
  const [form, setForm] = createStore({
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    gender: "",
  });

  const handleSubmit = (e) => {
    e.preventDefault();

    // 确保在浏览器环境下操作sessionStorage(避免SSR报错)
    if (typeof window !== "undefined") {
      // 存入用户提交的最新表单值
      sessionStorage.setItem('firstName', form.firstName);
      sessionStorage.setItem('lastName', form.lastName);
      sessionStorage.setItem('email', form.email);
      // 注意:明文存储密码存在安全风险,建议仅存储必要字段(如邮箱、姓名)
      sessionStorage.setItem('password', form.password);
      sessionStorage.setItem('gender', form.gender);
    }

    // 清空表单输入框
    setForm({
      firstName: "",
      lastName: "",
      email: "",
      password: "",
      gender: "",
    });

    // 执行发送验证邮件的逻辑
    // sendVerificationEmail(form.email, ...);
  };

  return { form, setForm, handleSubmit };
}

2. 读取逻辑的优化(可选)

在useResendEmail.jsx中,建议在需要使用值的时候再读取,并且增加空值判断:

export function useResendEmail() {
  const handleResend = () => {
    if (typeof window === "undefined") return;

    const firstName = sessionStorage.getItem('firstName');
    const lastName = sessionStorage.getItem('lastName');
    const email = sessionStorage.getItem('email');
    const password = sessionStorage.getItem('password');
    const gender = sessionStorage.getItem('gender');

    // 空值判断,避免无意义的请求
    if (!email) {
      console.error('未找到有效邮箱信息,请先完成注册表单提交');
      return;
    }

    // 执行重发邮件逻辑
    // resendVerificationEmail(email, firstName);
  };

  return { handleResend };
}

额外注意事项

  • sessionStorage是标签页会话级存储:关闭当前标签页后数据会被清空,并非保留到电脑关机;如果需要跨标签页或持久化存储,可改用localStorage。
  • 安全提醒:不要在sessionStorage中存储明文密码,哪怕是临时存储,建议仅保留发送邮件必需的字段(如邮箱、姓名),密码可在提交时直接使用,无需存储。
  • SSR环境兼容:如果你的SolidJS应用使用SSR(如SolidStart),必须判断typeof window !== "undefined"后再操作sessionStorage,避免服务器端执行时抛出错误。

内容的提问来源于stack exchange,提问作者Goune Kenfack

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:15:44