React中通过history.push传值后另一页面无法获取,正确实现方式是什么?
错误原因
你的写法存在三处核心错误:
history.push入参格式错误:react-router 要求自定义跳转参数必须放在state字段下,直接将id写在参数根层级不会被存入history实例- 错误调用
then方法:history.push是同步方法,返回值为undefined,没有Promise的then接口,此处代码会直接抛出类型错误,后续逻辑无法执行 - 跳转方式错误:你后续调用
window.location赋值会触发整页重加载,整个应用实例会重置,就算之前参数传对,存储在history中的临时状态也会全部丢失
正确实现方式
传参侧代码修改
const editById = (id) => { console.log(id); axios .post(`/getDocToEdit`, { id: id }) .then((RESPONSE) => { console.log(RESPONSE); // 写法1:两个参数,第一个为目标路由,第二个为state参数 this.props.history.push("/admin/services/替换为实际site值", { id: id }); // 写法2:单个对象参数也可 // this.props.history.push({ // pathname: "/admin/services/替换为实际site值", // state: { id: id } // }); console.log(id, " worked"); }) .catch((error) => { console.log(error); }); }
目标页取值代码
不要读取this.props.history.id,正确取值路径为:
console.log(this.props.history.location.state.id)
补充注意
如果用户在目标页手动刷新浏览器,存在state中的临时参数会丢失。如果需要支持刷新后仍能拿到id,可以选择两种方案:
- 将id拼到路由路径中,比如路由规则改为
/admin/services/:site/:id,跳转时把id拼到路径里,目标页通过this.props.match.params.id取值 - 将id存入
localStorage等本地存储,跳转后读取再清除
内容的提问来源于stack exchange,提问作者Gianluca
相关产品推荐
相关产品推荐

