ReactJS中完成身份认证后如何从登录页向Profile页面传数据
实现方案
1. 完善登录页传参逻辑
你现有的代码中state仅配置了username和password,补充gender字段即可:
<div className="d-flex justify-content-center mt-5"> {loginStatus=="Thanks For Logging In" ? <Navigate to={ { pathname: '/profile', state: { username: Username, password: 'Password', gender: Gender // 此处替换为你实际存储性别值的变量 } } } /> : <div> Login Components </div> } </div>
2. Profile页面接收参数
使用react-router提供的useLocation钩子即可读取传递的state数据:
import { useLocation } from 'react-router-dom' function Profile() { const location = useLocation() // 取出三个字段,添加默认值避免state为空时报错 const { username, password, gender } = location.state || {} // 后续业务逻辑直接使用上述三个变量即可 return ( <div> <p>用户名:{username}</p> <p>性别:{gender}</p> </div> ) }
注意事项
- 敏感数据如明文密码不要通过路由state长期传递,该方案仅适用于单次跳转的临时传参,页面刷新后state会自动丢失
- 如果需要跨页面持久化存储用户信息,建议结合token存在localStorage/sessionStorage或全局状态管理工具(Redux、Zustand等)中,密码不要明文持久化存储
内容的提问来源于stack exchange,提问作者Mario Thoumy
相关产品推荐
相关产品推荐

