我有一个支付功能,这是一个按钮,点击调用,如果用户没有登录,我想重定向该用户到签署组件。这是我的函数代码。
const PaymentMethod = ()=>{
if(!isAuthenticated())
{
toast.error('Please signin to continue');
history.push('/signin') //works properly
// return <Redirect to = '/signin' /> // not working properly
}
}
// isAuthenticated is a boolean function that look whether the user is signed in or not 发布于 2022-10-01 16:36:34
试一试
return <Redirect to = '/signin' /> 因为您必须呈现Redirect才能产生效果
发布于 2022-10-02 04:38:40
如果PaymentMethod是一个反应组件,那么history.push需要在具有适当依赖关系的useEffect钩子中调用,或者在回调函数中作为有意的副作用调用,而不是作为渲染体中的意外副作用调用。为了产生任何效果,需要从组件返回Redirect组件。
发出命令式重定向的useEffect示例:
const PaymentMethod = () => {
const history = useHistory();
React.useEffect(() => {
if (!isAuthenticated()) {
toast.error('Please sign in to continue');
history.replace('/signin');
}
}, [history, toast]);
...
};发出声明性重定向的<Redirect>示例:
const PaymentMethod = () => {
React.useEffect(() => {
if (!isAuthenticated()) {
toast.error('Please sign in to continue'); // <-- still a side-effect!!
}
}, [toast]);
if (!isAuthenticated()) {
return <Redirect to='/signin' />;
}
... regular JSX return ...
};如果PaymentMethod 是回调函数的,那么必须通过history.replace函数发出命令式重定向,从异步调用的回调返回JSX不会将其呈现给DOM。您也不应该将回调处理程序命名为React函数组件。这是为了消除任何混乱。
const history = useHistory();
...
const paymentMethodHandler = () => {
if (!isAuthenticated()) {
toast.error('Please sign in to continue');
history.replace('/signin');
}
};
...发布于 2022-10-01 16:39:20
看起来,<Redirect to = '/signin' />是一个组件,而不是一个可以调用的JS。组件需要呈现才能运行它们的JS。
如果您出于某种原因想要具体使用重定向组件,则必须在单击时将其放入DOM中。
https://stackoverflow.com/questions/73920030
复制相似问题