如何使用 history.push 传递道具
How to pass props with history.push
我有 2 个页面:betslip.jsx 和 receipt.jsx。
当在 betslip.jsx 中单击按钮时,我将用户重定向到 receipts.jsx,使用以下代码为 2 个道具赋值:
history.push({
state: { authorized:true, total:10},
pathname: '/receipt'
})
根据我的阅读,这应该有效,但收据中从未收到道具值,因为收据如下所示:
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>
)
}
授权还是false,总数还是0(它们的初始值)。
我是不是遗漏了什么明显的东西?请指教
在你的组件中试试这个
const location = useLocation();
const {authorized, total} = location.state;
收据组件
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>
)
}
答案是在您要定向到的页面内执行此操作:
const location = useLocation();
if(location.state){
authorized = location.state.authorized;
total = location.state.total;
} else{
if(!authorized){
return <Redirect to="/" />;
}
}
我有 2 个页面:betslip.jsx 和 receipt.jsx。
当在 betslip.jsx 中单击按钮时,我将用户重定向到 receipts.jsx,使用以下代码为 2 个道具赋值:
history.push({
state: { authorized:true, total:10},
pathname: '/receipt'
})
根据我的阅读,这应该有效,但收据中从未收到道具值,因为收据如下所示:
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>
)
}
授权还是false,总数还是0(它们的初始值)。
我是不是遗漏了什么明显的东西?请指教
在你的组件中试试这个
const location = useLocation();
const {authorized, total} = location.state;
收据组件
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>
)
}
答案是在您要定向到的页面内执行此操作:
const location = useLocation();
if(location.state){
authorized = location.state.authorized;
total = location.state.total;
} else{
if(!authorized){
return <Redirect to="/" />;
}
}