[英]How to pass props with history.push
我有 2 頁:betslip.jsx 和receipt.jsx。
當在 betslip.jsx 中單擊按鈕時,我將用戶重定向到收據.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>
)
}
Authorized 仍為 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="/" />;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.