diff --git a/src/components/ChangePasswordModal.jsx b/src/components/ChangePasswordModal.jsx new file mode 100644 index 0000000..eafbad1 --- /dev/null +++ b/src/components/ChangePasswordModal.jsx @@ -0,0 +1,151 @@ +import React, { useState } from 'react'; +import { useDispatch } from 'react-redux'; +import { useNavigate } from 'react-router-dom'; +import { changePasswordThunk } from '../store/auth/auth.thunk'; + +function ChangePasswordModal({ show, onClose }) { + const dispatch = useDispatch(); + const navigate = useNavigate(); + + const [formData, setFormData] = useState({ + old_password: '', + new_password: '', + confirm_password: '', + }); + + const [errors, setErrors] = useState({}); + const [isSubmitting, setIsSubmitting] = useState(false); + const [submitted, setSubmitted] = useState(false); + + const handleChange = (e) => { + const { name, value } = e.target; + setFormData({ + ...formData, + [name]: value.trim(), + }); + }; + + const validateForm = () => { + const newErrors = {}; + + if (!formData.old_password) { + newErrors.old_password = '请输入当前密码'; + } + + if (!formData.new_password) { + newErrors.new_password = '请输入新密码'; + } else if (formData.new_password.length < 6) { + newErrors.new_password = '新密码长度不能少于6个字符'; + } + + if (!formData.confirm_password) { + newErrors.confirm_password = '请确认新密码'; + } else if (formData.new_password !== formData.confirm_password) { + newErrors.confirm_password = '两次输入的密码不一致'; + } + + setErrors(newErrors); + return Object.keys(newErrors).length === 0; + }; + + const handleSubmit = async (e) => { + e.preventDefault(); + setSubmitted(true); + + if (validateForm()) { + setIsSubmitting(true); + try { + await dispatch( + changePasswordThunk({ + old_password: formData.old_password, + new_password: formData.new_password, + }) + ).unwrap(); + + // 成功后会由thunk中的代码重定向到登录页 + navigate('/login'); + } catch (error) { + // 错误处理已经在thunk中完成 + console.error('Change password failed:', error); + } finally { + setIsSubmitting(false); + } + } + }; + + if (!show) return null; + + return ( +
- 加载消息失败 -
{messageError}