在官方文档中,它说要访问传递到重定向到的组件的状态,您可以使用this.props.location.state
但是我没有使用类组件,因此我没有this.
.
如何访问重定向组件中的传递状态?
<Redirect
to={{
pathname: "/signin",
state: { from: props.location, alert: true },
}}
/>
以下函数标识在重定向时的状态中是否传递了警报。如果alert:true
它会显示<div>
let location = useLocation()
function DashboardRedirectAlert() {
if (location.state?.alert) {
return <div className="alert alert-warning">Please Signin first</div>;
} else {
return <></>;
}
}
当您尝试引用上述功能组件时,请确保始终返回某些内容。
在功能组件中,没有这个,所以你可以通过 props 直接使用任何状态。归因''
您不允许在功能组件中使用this
。真正的代码是:Props.location.state
.
事实上this
键盘删除了,因为在类组件中,当我们想要达到函数和属性以及状态使用this
但你使用功能组件时,所以不需要使用它。
它在功能组件中工作得很好。访问重定向的 URL 中的值 用
{( typeof props.location.state != "undefined" ) && props.location.state }
您还需要添加未定义的检查,以防您在没有重定向的情况下访问页面
在功能组件中,state
prop 在从useLocation()
钩返回的location
对象上可用。
此示例使用可选链接来测试状态是否存在并包含myVariable
。
function LinkToComponent(props) {
return (
<Link
to={{
pathname: `/myRoute/${props.id}`,
state: { myVariable: true },
}}
>
Click me
</Link>
);
}
function LinkedToComponent(props) {
const location = useLocation();
// will render only if `myVariable` was passed as `true` in Link state
{
location.state?.myVariable && <p>my variable is true</p>;
}
}