MERN栈React组件间传值:点击按钮将收货地址数据传递到/confirm页面
实现方案
方案1:React Router 路由传参(推荐,适用于单页应用无刷新跳转场景)
你当前用原生<a>标签跳转是无法携带组件内状态的,改用React Router的路由传参即可实现,操作步骤如下:
- 修改CreateAddress组件的PROCEED按钮代码
将原来的原生a标签替换为React Router的Link组件,通过state属性携带收货地址数据:
// 先引入Link组件 import { Link } from 'react-router-dom' // 替换原有PROCEED按钮代码 <Link to="/confirm" state={{ shippingInfo: { address: this.state.address, city: this.state.city, phoneNo: this.state.phoneNo, postalCode: this.state.postalCode, country: this.state.country } }} style={{textDecoration:'none',color:'white'}} > <button id="shipping_btn" type="button" className = "btn btn-block py-3" > PROCEED </button> </Link>
注意要将按钮的type改为button,避免触发表单默认提交逻辑。
2. 在/confirm页面获取传递的参数
如果confirm页是函数组件,用useLocation钩子取值:
import { useLocation } from 'react-router-dom' function ConfirmPage() { const location = useLocation() // 拿到传递的收货地址数据 const shippingInfo = location.state?.shippingInfo console.log(shippingInfo) // 后续业务逻辑 }
如果confirm页是类组件,封装高阶组件获取路由参数即可。
方案2:localStorage 持久化存储(适用于刷新页面数据不丢失的场景)
如果希望用户刷新页面后数据依然存在,可以用本地存储实现:
- 给PROCEED按钮添加点击事件,存储数据到本地
// CreateAddress组件新增方法 handleProceed = () => { const {address,city,phoneNo,postalCode,country} = this.state localStorage.setItem('shippingInfo', JSON.stringify({address,city,phoneNo,postalCode,country})) } // 修改按钮代码 <button id="shipping_btn" type="button" className = "btn btn-block py-3" onClick={this.handleProceed} > <a href = "/confirm" style={{textDecoration:'none',color:'white'}}>PROCEED</a> </button>
- 在confirm页面取值
const shippingInfo = JSON.parse(localStorage.getItem('shippingInfo')) // 数据用完不需要留存时可以删除 // localStorage.removeItem('shippingInfo')
额外优化建议
如果希望用户只点击一次PROCEED就同时完成「地址存数据库」和「跳转确认页」两个操作,可以把两个逻辑合并:
// CreateAddress组件新增方法 onProceed = (e) => { e.preventDefault() const {address,city,phoneNo,postalCode,country} = this.state; const data = {address,city,phoneNo,postalCode,country} axios.post("http://localhost:5000/address/save",data).then((res)=>{ if(res.data.success){ // 保存成功后再跳转 this.props.navigate('/confirm', {state: {shippingInfo: data}}) } }) }
这样可以省略单独的SAVE按钮,减少用户操作步骤。
内容的提问来源于stack exchange,提问作者Vibhu Jayawardane
相关产品推荐
相关产品推荐

