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

React项目中密码更新后无法跳转至登录页的问题求助

问题:密码更新成功后无法跳转至/login路由

React+Redux项目中,密码更新功能已正常生效(可获取新token,密码成功更新),但点击“Update Password”按钮后页面无法跳转至/login路由。尝试调整useNavigate及路由配置后问题仍未解决,相关组件代码如下:

import React, { useEffect, useState } from 'react'
import { FaFingerprint } from 'react-icons/fa'
import { useDispatch, useSelector } from 'react-redux'
import { useNewPasswordMutation } from '../Redux/Api/userApiSlice'
import { Link, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'

import '../styles/Login.css'
import { setCredentials } from '../Redux/Api/authSlice'

export default function ResetPassword() {
    // 状态变量拼写错误:newPasswword 多了一个w
    const [newPasswword, setNewPassword] = useState('')

    const dispatch = useDispatch()
    const navigate = useNavigate()

    const [newPassword] = useNewPasswordMutation()
    // 假设auth slice中定义了addNewPassword,但未导入对应的action creator
    const { addNewPassword } = useSelector((state) => state.auth);

    useEffect(() => {
        if (addNewPassword)
            navigate('/login')
    }, [navigate, addNewPassword])

    const newPasswordHandler = async (e) => {
        e.preventDefault()

        try {
            // 提交参数错误:使用了未定义的password变量,应该是newPasswword(但变量名本身错误)
            const res = await newPassword({ password }).unwrap()
            dispatch(setCredentials({ ...res }))
            // 若未正确导入addNewPassword action,此dispatch无效
            dispatch(addNewPassword({ ...res }))
            navigate('/login')
        } catch (err) {
            toast.error(err?.data?.message || err.error)
        }
    }

    return (
        <div className="container">
            <div className="row w-500">
                <div className="col-sm-12 d-flex">
                    <div className="login-card card-block auth-body">
                        <div className="authbox">
                            <div className="brand-logo text-center">Bubllee</div>
                            <p className='text-secondary text-center' style={{ fontFamily: 'Indie Flower', fontSize: '12px' }} >Please enter your new password</p>
                            <br />
                            <div className="col-12">
                                <form action="" className='w-100' onSubmit={newPasswordHandler}>
                                    <div className="input-group">
                                        <span className='input-group-addon'>
                                            <FaFingerprint className='icon iconfont' />
                                        </span>
                                        <input type="password" placeholder='Enter New Password' className='form-control' required autoComplete='off'
                                            value={newPasswword} onChange={(e) => setNewPassword(e.target.value)} style={{ borderRadius: '20px' }} />
                                    </div>
                                    <div className="links text-right ">
                                        <div className="registration-link">
                                            <p>Go back to</p>
                                            <Link to='/' className='text-left f-w-600'>
                                                <p className='iconfont iconfont-lock'>Sign In</p>
                                            </Link>
                                        </div>
                                    </div>
                                    <br />
                                    <div className="m-t-20">
                                        <button type='submit' className="btn btn-primary btn-md btn-block m-b-10 signupbtn">Update Password</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

解决方案

1. 修正状态变量拼写错误

状态变量名newPasswword多了一个w,导致提交时参数不匹配,同时input的value绑定也需同步修正:

const [newPassword, setNewPassword] = useState('')
// ...
<input type="password" placeholder='Enter New Password' className='form-control' required autoComplete='off'
    value={newPassword} onChange={(e) => setNewPassword(e.target.value)} style={{ borderRadius: '20px' }} />

2. 修正提交请求的参数

提交时需传入正确的密码状态变量,替换未定义的password:

const res = await newPassword({ password: newPassword }).unwrap()

3. 优化跳转逻辑(推荐使用RTK Query的mutation状态)

无需依赖自定义的Redux状态,直接监听RTK Query mutation的成功状态来触发跳转,更可靠:

// 解构出mutation的状态
const [newPassword, { isSuccess }] = useNewPasswordMutation()

// 监听isSuccess状态,成功时跳转
useEffect(() => {
    if (isSuccess) {
        navigate('/login')
    }
}, [navigate, isSuccess])

4. 清理无效的Redux dispatch

若addNewPassword未在authSlice中定义或未正确导入,删除该行无效的dispatch:

// 移除此行(若无需更新该状态)
// dispatch(addNewPassword({ ...res }))

修复后的完整代码

import React, { useEffect, useState } from 'react'
import { FaFingerprint } from 'react-icons/fa'
import { useDispatch, useSelector } from 'react-redux'
import { useNewPasswordMutation } from '../Redux/Api/userApiSlice'
import { Link, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'

import '../styles/Login.css'
import { setCredentials } from '../Redux/Api/authSlice'

export default function ResetPassword() {
    const [newPassword, setNewPassword] = useState('')

    const dispatch = useDispatch()
    const navigate = useNavigate()

    // 解构获取mutation的成功状态
    const [newPasswordMutation, { isSuccess }] = useNewPasswordMutation()

    useEffect(() => {
        // 监听mutation成功状态,触发跳转
        if (isSuccess) {
            navigate('/login')
        }
    }, [navigate, isSuccess])

    const newPasswordHandler = async (e) => {
        e.preventDefault()

        try {
            // 传入正确的密码参数
            const res = await newPasswordMutation({ password: newPassword }).unwrap()
            dispatch(setCredentials({ ...res }))
            // 可选:若mutation状态未及时更新,可在此添加兜底跳转(但推荐依赖isSuccess)
            // navigate('/login')
        } catch (err) {
            toast.error(err?.data?.message || err.error)
        }
    }

    return (
        <div className="container">
            <div className="row w-500">
                <div className="col-sm-12 d-flex">
                    <div className="login-card card-block auth-body">
                        <div className="authbox">
                            <div className="brand-logo text-center">Bubllee</div>
                            <p className='text-secondary text-center' style={{ fontFamily: 'Indie Flower', fontSize: '12px' }} >Please enter your new password</p>
                            <br />
                            <div className="col-12">
                                <form action="" className='w-100' onSubmit={newPasswordHandler}>
                                    <div className="input-group">
                                        <span className='input-group-addon'>
                                            <FaFingerprint className='icon iconfont' />
                                        </span>
                                        <input type="password" placeholder='Enter New Password' className='form-control' required autoComplete='off'
                                            value={newPassword} onChange={(e) => setNewPassword(e.target.value)} style={{ borderRadius: '20px' }} />
                                    </div>
                                    <div className="links text-right ">
                                        <div className="registration-link">
                                            <p>Go back to</p>
                                            <Link to='/' className='text-left f-w-600'>
                                                <p className='iconfont iconfont-lock'>Sign In</p>
                                            </Link>
                                        </div>
                                    </div>
                                    <br />
                                    <div className="m-t-20">
                                        <button type='submit' className="btn btn-primary btn-md btn-block m-b-10 signupbtn">Update Password</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

内容的提问来源于stack exchange,提问作者Branimir Ban

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:02:16