簡體   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