繁体   English   中英

将redux存储绑定到函数

[英]Binding a redux store to a function

我将这些路径包含在checkAuth方法中,以查看访问者的会话状态。 为了保持代码清洁,我将checkAuth方法分离为一个单独的文件,并将其导入带有路由声明的文件中:

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需要store读取状态并调度一些操作,所以我不确定如何传递它。 我尝试使用bind,你可以在我的代码中看到但是console.log(this)在方法中返回undefined。

这是checkAuth代码:

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;
    ....
};

您正在使用箭头功能,因此您无法bind任何内容bind到它们。 这就是你的控制台调用返回undefined的原因。

您可以直接在checkAuth模块中导入商店:

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

并将其简单地用作onEnter={checkAuth}

或者你可以做一个工厂:

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

并将其传递给商店: onEnter={checkAuth(store)}

或者只使用普通功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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