ReactJs如何跳转至其他功能组件并传值,传递ID为何获取为undefined
问题原因及修复方案
错误点整理
- 参数取值错误+列表渲染缺失:你的
data是存储所有用户数据的数组类型,数组本身不存在usersID属性,只有数组内的单个用户对象才带有这个字段。同时你当前代码只返回了一个Expand按钮,没有遍历data为每个用户生成对应的操作按钮,根本无法绑定单个用户的ID。 - 路由组件配置不匹配:你在
routes.js中配置/app/CustomerDetails路径对应的渲染组件是<CustomerDetails />,但你写的接收参数的详情页组件名为CustomerProfile,两个组件没有对应上,跳转后实际渲染的不是你写的读ID的组件,自然拿不到参数值。 - 详情页请求逻辑缺陷:
CustomerProfile中的useEffect没有将id加入依赖数组,就算后续拿到ID也不会重新触发数据库请求;同时没有做state存在性校验,页面刷新后state丢失会直接抛出异常。
修复后的代码示例
1. 修正CustomerList组件
需要遍历用户列表为每个用户生成对应的Expand按钮,绑定对应ID:
const CustomerList = () => { const navigate = useNavigate(); const [data, setData] = useState([]); useEffect(() => { const list = [] firebase.firestore().collection("Users").get().then((userSnapshot) => { userSnapshot.forEach((doc) => { const {powerAccount,first_name,registerDate,email,company,country,phone} = doc.data(); list.push({ usersID:doc.id, powerAccount, first_name, registerDate, email, company, country, phone, }); }) setData(list); }) },[]); return ( // 这里遍历data数组,为每个用户生成一行信息+对应的Expand按钮 <div> {data.map(user => ( <div key={user.usersID} style={{display: 'flex', gap: '10px', margin: '10px 0'}}> <span>{user.first_name} - {user.email}</span> <Button color="primary" variant="contained" onClick={()=>{ // 传当前遍历到的用户的usersID navigate('/app/CustomerDetails', { state: { id: user.usersID } }); }} > Expand </Button> </div> ))} </div> ) }
2. 修正路由配置
把routes.js中对应路径的组件和你实际写的详情页组件名对齐,这里举例把路由配置的组件改为CustomerProfile:
// 找到app下的children对应配置,修改为 { path: 'CustomerDetails', element: <CustomerProfile /> },
3. 修正CustomerProfile组件
加状态判空和依赖项:
const CustomerProfile = (props) => { const {state} = useLocation(); const id = state?.id; // 可选链判空,避免state不存在时报错 console.log(id) const [name,setName] = useState(""); useEffect(() => { // 只有id存在时才发起请求 if(!id) return firebase.firestore().collection("Users").doc(id).get().then((userSnapshot) => { if(userSnapshot.exists) { console.log(userSnapshot.data()) setName(userSnapshot.data().first_name) } }) },[id]); // 把id加入依赖数组,id变化时重新触发请求 }
内容的提问来源于stack exchange,提问作者motionless570
相关产品推荐
相关产品推荐

