简体   繁体   中英

Binding a redux store to a function

I have these routes that I want wrapped into a checkAuth method to see the session state of the visitor. To keep the code clean I separated the checkAuth method to a separate file and imported it into the file with routes declaration:

import {checkAuth} from 'helpers/core'

export default ( store ) => {
    return (
        <Router history={browserHistory} onEnter={checkAuth.bind(store)}>
            <Route path={AUTH_ROUTE} component={AuthLayout}>
                <IndexRoute component={AuthView}/>
            </Route>

            <Route component={CoreLayout}>
                <Route path={DASHBOARD_ROUTE} component={AuthView}/>
            </Route>
        </Router>
    )
}

checkAuth needs the store to read state and also dispatch some actions so I'm unsure how to pass it. I tried with bind as you can see in my code but console.log(this) returns undefined inside the method.

Here's the checkAuth code:

export const checkAuth = ( desiredRoute, redirect ) => {
    console.log(this);// returns undefined
    const state = this.getState();// Cannot read property 'getState' of undefined
    const isAuthenticated = state.auth.loggedIn;
    ....
};

You're using arrow functions, so you can't bind anything to them. That's why your console call returns undefined .

You can import the store directly in your checkAuth module:

import store from 'path/to/store';
export const checkAuth = ( desiredRoute, redirect ) => {
  const state = store.getState();
}

And use it simply as onEnter={checkAuth} .

Or you can make a factory:

export const checkAuth = ( store ) => ( desiredRoute, redirect ) => {
  const state = store.getState();
}

And pass it the store: onEnter={checkAuth(store)} .

Or just use normal functions.

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