2016-11-20 122 views
1

我正在查看使用react,redux和auth0作爲登錄場景的auth0示例項目here。不過我有點困惑,我們稱之爲this.props.doAuthentication()對使用​​react和redux的auth0鎖示例感到困惑

// App.js 
import { loginUser, fetchQuote, doAuthentication, fetchSecretQuote } from '../actions' 

// add a constructor 
constructor(props) { 
    super(props) 
    this.props.doAuthentication() 
    } 

這個特殊的例子下面是動作定義

// actions.js 

... 

const lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_CLIENT_DOMAIN'); 

export function login() { 
    // display lock widget 
    return dispatch => { 
    lock.show(); 
    } 
} 

// Listen to authenticated event and get the profile of the user 
export function doAuthentication() { 
    return dispatch => { 
     lock.on("authenticated", function(authResult) { 
      lock.getProfile(authResult.idToken, function(error, profile) { 

       if (error) { 
       // handle error 
       return dispatch(lockError(error)) 
       } 

       localStorage.setItem('profile', JSON.stringify(profile)) 
       localStorage.setItem('id_token', authResult.idToken) 
       return dispatch(lockSuccess(profile)) 
      }); 
     }); 
    } 
} 

... 

我是新來的終極版,所以也許這是一個明顯的答案,但

  1. doAuthentication綁定到App.js中的道具在哪裏?假設App.js是頂級的根應用程序組件。

  2. 不做認證生成一個需要調度參數的函數嗎?爲什麼我們不使用doAuthentication()的返回函數在構造函數中做任何事情?如果我們不將返回的函數賦值給任何東西,this.props.doAuthentication是否會持續存在或有任何影響?它不應該像doAuthentication()(someDispatchFunction)這樣的調度功能從哪裏來?

回答

0

1.在App.js的道具中綁定了哪些認證?假設App.js是頂級的根應用程序組件。

答案: 動作doAuthentication結合使用稱爲redux-thunk中間件App成分的props用。

let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore) 

let store = createStoreWithMiddleware(quotesApp) 

以上兩行代碼將爲您完成。請閱讀here爲什麼需要redux-thunk

2.Doesn't doAuthentication生成一個函數,需要一個調度參數?爲什麼我們不使用doAuthentication()的返回函數在構造函數中做任何事情?如果我們沒有將返回的函數賦值給任何東西,this.props.doAuthentication是否會保留任何東西或有任何影響?它不應該像doAuthentication()(someDispatchFunction)這樣的派遣函數從哪裏來?

答案: 2.1是,它是由doAuthentication函數返回的函數需要dispatch方法,以能夠在第一參數。

2.2,2.3這裏doAuthentication動作創建者的工作是創建一個Redux action,它只會監聽名爲authenticated的事件。當我們調用doAuthentication動作創建器時,它將返回一個Redux action函數,該函數接受作爲第一個參數的dispatch方法和接受第二個方法的getState方法。這些參數將由redux-thunnk中間件傳遞。

redux-thunk中間件將調用了Redux作用,這是從doAuthentication調用返回,因爲它是connet -ed。否則,我們必須派遣由doAuthentication像下面返回的動作,

this.props.dispatch(doAuthentication()) 

2.4你提到doAuthentication()(someDispatchFunction)我們可以做的,但考慮這句話

如果終極版咚中間件被啓用,任何當你試圖用 調度一個函數而不是一個動作對象時,中間件將會調用該函數,調度方法本身作爲第一個參數。

而且,你可以找到有關redux-thunk詳細的信息與此answer