React Router Redirect Conditional

后端 未结 3 834
生来不讨喜
生来不讨喜 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条回答
  • 2021-02-10 19:38

    Like Purgatory said you can do it without using <Redirect />, but otherwise you could make your component a stateful component and then do a conditional render like so

    render() {
        !this.state.redirect ? 
          <button onClick={this.saveAndContinue}>Save and Continue</button> :
          <Redirect to='/other_tab'>
      }
    

    And let the saveAndContinue() change the component state.

    saveAndContinue () {
        var valid = validator.validate(this.props.form)
        if (valid) {
          axios.post('/path')
          this.setState({redirect: true});
        } else {
          validator.showErrors()
        }
      }
    

    When the state changes it would cause a re-render and this time the <Redirect /> would be rendered.

    Note: I didn't actually run this code snippet, so it may contain (hopefully minor) errors.

    0 讨论(0)
  • 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<IConditionalRedirectProps> = (props) => {
        const {shouldRedirect, to, children} = props;
    
        if (shouldRedirect) {
            console.log('redirecting');
            return <Redirect to={to}/>
        } else {
            return (
                <>
                    {children}
                </>
            )
        }
    };
    

    Usage:

    <ConditionalRedirect shouldRedirect={isButtonClicked()}
                                 to={'some url'}>
        <Normal Elements here>
    </ConditionalRedirect>
    
    0 讨论(0)
  • 2021-02-10 19:39

    As discussed you should have access to the history object via this.props.history as described here.

    If you look into the push function this will redirect you to any route you need. For example:

    // Use push, replace, and go to navigate around.
    this.props.history.push('/home', { some: 'state' })
    

    https://reacttraining.com/react-router/web/api/history

    0 讨论(0)
提交回复
热议问题