[英]How to pass props with history.push
I have 2 pages: betslip.jsx and receipt.jsx.我有 2 页:betslip.jsx 和receipt.jsx。
When a button is clicked in betslip.jsx I redirect the user to receipts.jsx, giving value for 2 props with the following code:当在 betslip.jsx 中单击按钮时,我将用户重定向到收据.jsx,使用以下代码为 2 个道具赋值:
history.push({
state: { authorized:true, total:10},
pathname: '/receipt'
})
From my reading, this SHOULD work but the prop values are never received in receipts as receipts look like this:根据我的阅读,这应该有效,但收据中永远不会收到道具值,因为收据看起来像这样:
export default function Receipt({authorized, total}) {
console.log('authorized: ', authorized);
console.log('total: ', total);
if(!authorized){
return <Redirect to="/" />;
}
return (
<div>
<h1>hello</h1>
</div>
)
}
Authorized is still false, the total is still 0 (their initial values). Authorized 仍为 false,总数仍为 0(它们的初始值)。
Am I missing something obvious here?我在这里遗漏了一些明显的东西吗? Pls advice
请建议
Try this inside your component在你的组件中试试这个
const location = useLocation();
const {authorized, total} = location.state;
Receipt component收据组件
export default function Receipt(props) {
const location = useLocation();
const {authorized, total} = location.state;
console.log('authorized: ', authorized);
console.log('total: ', total);
if(!authorized){
return <Redirect to="/" />;
}
return (
<div>
<h1>hello</h1>
</div>
)
}
The answer is to do this inside of the page you want to direct to:答案是在您要定向到的页面内执行此操作:
const location = useLocation();
if(location.state){
authorized = location.state.authorized;
total = location.state.total;
} else{
if(!authorized){
return <Redirect to="/" />;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.