React15.6与react-router4中多来源页面返回按钮跳转实现
解决React Router 4中动态返回来源页面的问题
这个场景我之前也碰到过,在react-router 4里要实现这种动态返回原来源的需求,核心思路就是在导航时记录来源页面的路径,通过路由的state来传递这个关键信息,下面是具体的实现步骤:
1. 在来源页面(A/B)跳转时携带来源标识
当用户从A或B页面跳转到form1时,需要在导航操作里附带当前页面的路径,让后续页面能识别跳转来源。你可以用两种方式实现:
方式一:通过history.push方法传递
在A页面的跳转逻辑中:
// A页面组件内 handleGoToForm1 = () => { this.props.history.push('/form1', { from: '/A' }); };
在B页面的跳转逻辑中:
// B页面组件内 handleGoToForm1 = () => { this.props.history.push('/form1', { from: '/B' }); };
方式二:使用<Link>组件的对象格式to属性
如果是通过链接跳转,直接给to传一个包含state的对象即可:
// A页面中 <Link to={{ pathname: '/form1', state: { from: '/A' } }}>进入表单1</Link> // B页面中 <Link to={{ pathname: '/form1', state: { from: '/B' } }}>进入表单1</Link>
2. 在form1页面处理BACK按钮逻辑
在form1页面,我们需要读取路由state里的来源路径,点击BACK按钮时跳转到对应的页面。同时要考虑用户直接访问form1的情况(此时没有来源信息,设置一个默认返回路径,比如/A):
// form1页面组件内 handleBack = () => { const { location, history } = this.props; // 获取来源路径,无来源时用默认值兜底 const backPath = location.state?.from || '/A'; history.push(backPath); }; // 渲染BACK按钮 <button onClick={this.handleBack}>BACK</button>
3. 从form1跳转到form2时传递来源信息
为了保证form2的BACK按钮跳回form1后,form1的BACK仍能正确返回原来源,需要在跳转到form2时把来源信息一起传递过去:
// form1页面中跳转到form2的逻辑 handleGoToForm2 = () => { const { location, history } = this.props; history.push('/form2', { from: location.state?.from }); };
或者用<Link>组件实现:
<Link to={{ pathname: '/form2', state: { from: this.props.location.state?.from } }}>NEXT</Link>
4. form2页面的BACK按钮逻辑
form2的BACK按钮只需要跳回form1就好,因为form1已经保存了完整的来源信息:
// form2页面组件内 handleBack = () => { this.props.history.push('/form1'); }; // 渲染BACK按钮 <button onClick={this.handleBack}>BACK</button>
这样就能完美实现需求:从A进入form1→form2后,点击BACK会回到form1,再点击BACK回到A;从B进入的话则会回到B,完全适配多来源的场景。
内容的提问来源于stack exchange,提问作者Abhijeet Srivastava
相关产品推荐
相关产品推荐

