简体   繁体   中英

How to implement routing from and to root (index.js) in react with redux

I'm programming a react server webpage, trying to redirect from index.js (ie: localhost:3000) to Login page: (localhost:3000/login), and from login to index (in case of failed login). What do I need to write in index.js and login.js?

This is for a react based app, using also redux framework. I've tried a few ways including setting up a BrowserRouter etc. All won't really do the redirecting.

My current code is this:

in index.js:

class Index extends Component {
    static getInitialProps({store, isServer, pathname, query}) {
    }

    render() {
        console.log(this.props);
        //const hist = createMemoryHistory();
        if (!this.props.isLoggedIn){
            return(<Switch><Route exact path = "/login"/></Switch>)
        }
                else{...}

in login.js:

render() {
        console.log(this.props);
        if (fire.auth().currentUser != null) {
            var db = fire.firestore();
            db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
                this.props.dispatch({ type: 'LOGIN', user: doc.data() });
            })
        }
        const { isLoggedIn } = this.props
        console.log(isLoggedIn)

        if (isLoggedIn) return <Redirect to='/' />

I except the root to redirect to login if no session is on, and login to redirect to root once there is a successful login. I am currently getting "You should not use <Switch> outside a <Router>" at index (I have tried to wrap with BrowserRouter, ServerRouter, Router. the first says it needs DOM history. adding history does not change error. two others do not error but are blank display on browser.) and "ReferenceError: Redirect is not defined" at login.

Any help will be appreciated.

As of now you're trying to return a route declaration wrapped in a Switch component. If you want to redirect the user to the /login page if hes not logged in, you need the route to be declared higher up in the component hierarchy, and then you would be able to return the <Redirect /> component. Either way, I would suggest you check out the react router documentation to see how they do authentication.

https://reacttraining.com/react-router/web/example/auth-workflow

you can use a HOC ( Higher-Order Components ) something like this

export default ChildComponent => {
    class ComposedComponent extends Component {

        componentWillMount() {
            this.shouldNavigateAway();
        }
        componentWillUpdate() {
            this.shouldNavigateAway();
        }
        shouldNavigateAway() {
            if (!this.props.authenticated) {
                this.props.history.push('/')
            }
        }

        render() {
            return <ChildComponent {...this.props} />
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM