Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

reactjs - React Router v4 Redirecting on form submit

Brand new to react, Attempting to redirect to a "homepage" after clicking submit on a "login" page. Tried to follow the react router tutorial.

When I click the submit button on the form and console log the state and fakeAuth.isAuthenticated, they both return true. However, the redirect is not firing.

Login.js

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            portalId: "",
            password: "",
            redirectToReferrer: false
        }

        this.handleSubmit = this.handleSubmit.bind(this);
    }


    handleSubmit(e) {
        fakeAuth.authenticate(() => {
            this.setState({
                portalId: this.refs.portalId.value,
                password: this.refs.password.value,
                redirectToReferrer: true
            })
        })
        e.preventDefault();
    }


    render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer === true) {
            <Redirect to="/home" />
        }

Routes.js

export const fakeAuth = {
    isAuthenticated: false,
    authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb, 100)
    },
    signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb, 100)
    }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={() => (
        fakeAuth.isAuthenticated === true
        ? <Component {...this.props}/>
        : <Redirect to="/" />
    )}/> 
)


export default () => (
    <BrowserRouter>
        <div>
            <Navbar />
            <Switch>
                <Route path="/" exact component={Login} />
                <Route path="/register" exact component={Register} />
                <Route path="/home" exact component={Home} />
            </Switch>
        </div>
    </BrowserRouter>
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to return Redirect in render method (otherwise it will not be rendered and as a result redirection will not happen):

  render() {
        const redirectToReferrer = this.state.redirectToReferrer;
        if (redirectToReferrer) {
            return <Redirect to="/home" />
        }
        // ... rest of render method code
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...