简体   繁体   中英

How to pass props with history.push

I have 2 pages: betslip.jsx and 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:

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).

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="/" />;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM