【问题标题】:How to pass props with history.push如何使用 history.push 传递道具
【发布时间】:2021-07-23 13:40:43
【问题描述】:

我有两页:betslip.jsx 和receipt.jsx。

当点击 betslip.jsx 中的按钮时,我会将用户重定向到receipts.jsx,并使用以下代码为 2 个 props 赋值:

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(它们的初始值)。

我在这里遗漏了什么明显的东西吗?请指教

【问题讨论】:

标签: javascript reactjs react-router react-props


【解决方案1】:

答案是在您要定向到的页面内执行此操作:

const location = useLocation();
if(location.state){
    authorized = location.state.authorized;
    total = location.state.total;
} else{
    if(!authorized){
        return <Redirect to="/" />;
    }
}

【讨论】:

    【解决方案2】:

    在你的组件中试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2021-05-08
      • 2021-11-20
      • 2020-05-14
      相关资源
      最近更新 更多