React Router Redirect Conditional

后端 未结 3 845
生来不讨喜
生来不讨喜 2021-02-10 19:10

I\'m trying to make a button that only redirects the user to a new page after validation is completed correctly.

Is there a way of doing something like this? How to I g

3条回答
  •  Happy的楠姐
    2021-02-10 19:38

    I needed to do this today. Here's my code, mind i decided to make this a HOC that you can choose to wrap or not wrap. For use cases that have multiple redirect cases you'll definitely want to use this inline instead of as a wrapper.

    import React from 'react';
    import {Redirect} from 'react-router';
    
    interface IConditionalRedirectProps {
        shouldRedirect: boolean,
        to: string
    }
    
    export const ConditionalRedirect: React.FC = (props) => {
        const {shouldRedirect, to, children} = props;
    
        if (shouldRedirect) {
            console.log('redirecting');
            return 
        } else {
            return (
                <>
                    {children}
                
            )
        }
    };
    

    Usage:

    
        
    
    

提交回复
热议问题