2016-11-20 23 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