ReactJS兄弟组件状态传递:ID扫描考勤系统实现方案
如何在React路由跳转时给兄弟组件传递状态值
嘿,你的场景很典型——通过路由跳转到兄弟组件,还不想嵌套渲染,其实用React Router的跳转传参就能轻松搞定,给你两种最实用的方案:
方案一:用路由跳转的state传值 推荐(参数不暴露在URL)
这种方式不会把参数显示在浏览器地址栏里,适合不需要公开的业务参数,比如你这里的SubFacKey。
第一步:修改classroom.js里的跳转代码
把SubFacKey打包到跳转的state里就行,修改你代码里的history.push部分:
.then(() => { this.setState({ scanningCardToggle: false, isToggle: false }); // 把SubFacKey放到state里传递 this.props.history.push({ pathname: ROUTES.ATTENDEES, state: { subFacKey: stuCardInfoObj.SubFacKey } }); });
第二步:在attendees.js里取到这个值
如果你的attendees是类组件,直接通过this.props.location.state就能拿到:
componentDidMount() { // 用可选链操作符避免state不存在时报错 const subFacKey = this.props.location.state?.subFacKey; if (subFacKey) { // 拿到值后就可以做你需要的业务逻辑,比如操作Firebase之类的 console.log('拿到的SubFacKey:', subFacKey); } }
要是函数组件的话,用useLocation钩子就行:
import { useLocation } from 'react-router-dom'; function Attendees() { const location = useLocation(); const subFacKey = location.state?.subFacKey; // 这里写你的业务逻辑 return ( // 组件渲染内容 ); }
方案二:用URL路由参数传值 参数会显示在地址栏
如果这个SubFacKey是可以公开的,也可以把它作为URL的一部分传递,好处是刷新页面不会丢失参数。
第一步:先改路由配置
在你的路由文件里,把ATTENDEES的路由改成带参数的形式:
// 旧的路由可能是这样: // <Route path="/attendees" component={Attendees} /> // 改成带参数的: <Route path="/attendees/:subFacKey" component={Attendees} /> // 要是用React Router v6+的element写法: <Route path="/attendees/:subFacKey" element={<Attendees />} />
第二步:修改classroom.js的跳转代码
把SubFacKey拼到跳转的URL里:
.then(() => { this.setState({ scanningCardToggle: false, isToggle: false }); this.props.history.push(`${ROUTES.ATTENDEES}/${stuCardInfoObj.SubFacKey}`); });
第三步:在attendees.js里获取参数
类组件用this.props.match.params:
componentDidMount() { const subFacKey = this.props.match.params.subFacKey; // 后续业务逻辑 }
函数组件用useParams钩子:
import { useParams } from 'react-router-dom'; function Attendees() { const { subFacKey } = useParams(); // 这里处理你的业务 return ( // 组件内容 ); }
小提醒
- 用
state传值的话,用户刷新页面后这个值会丢失(因为存在内存里),如果需要刷新后还能保留,要么用URL参数,要么把值存到localStorage/sessionStorage里临时存一下。 - 要是你的项目用了Redux、Zustand这类状态管理库,也可以把
SubFacKey存到全局状态里,这样不管哪个组件都能直接拿,适合多个组件需要共享这个值的场景。
内容的提问来源于stack exchange,提问作者Tirth Patel
相关产品推荐
相关产品推荐

