对使用 react 和 redux 的 auth0 锁示例感到困惑

Confused about an auth0 lock example using react and redux

我正在查看 auth0 示例项目以了解在登录场景中使用 react、redux 和 auth0 here。但是,我对这个我们称之为 this.props.doAuthentication()

的特定示例感到有些困惑
// 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))
            });
      });
    }
}

...

我是 redux 的新手所以也许这是一个显而易见的答案但是

  1. doAuthentication 在哪里绑定到 App.js 中的道具?假设 App.js 是顶级根应用程序组件。

  2. doAuthentication 不会生成需要分派参数的函数吗?为什么我们不使用 doAuthentication() 返回的函数在构造函数中做任何事情?如果我们不将返回的函数分配给任何东西,this.props.doAuthentication 是否会保留任何东西或产生任何影响?不应该是类似doAuthentication()(someDispatchFunction)这个派发函数是从哪里来的吗?

1.Where doAuthentication 是否绑定到 App.js 中的道具?假设 App.js 是顶级根应用程序组件。

答案: 动作 doAuthentication 使用名为 redux-thunk.

的中间件与 App 组件的 props 绑定
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)

let store = createStoreWithMiddleware(quotesApp)

以上两行代码就可以为您完成。阅读 为什么需要 redux-thunk

2.DoesndoAuthentication 是否生成了一个需要调度参数的函数?为什么我们不使用 doAuthentication() 中的 returned 函数在构造函数中做任何事情?如果我们不将 returned 函数分配给任何东西,this.props.doAuthentication 是否会保留任何东西或产生任何效果?不应该是doAuthentication()(someDispatchFunction)之类的吗 这个派发函数是从哪里来的?

答案: 2.1 是的,由 doAuthentication 函数 return 编辑的函数需要一个 dispatch 方法作为第一个参数。

2.2, 2.3 这里 doAuthentication 动作创建者的工作是创建一个 Redux action,它只监听名为 authenticated 的事件。当我们调用 doAuthentication 动作创建器时,它 return 是一个 Redux action 函数,它接受 dispatch 方法作为第一个参数,getState 方法作为第二个参数。参数将由 redux-thunnk 中间件传递。

redux-thunk 中间件将从 doAuthentication 调用中调用 return 的 redux 操作,因为它是 connet-ed。否则我们必须像下面那样发送由 doAuthentication 编辑的 return 操作,

this.props.dispatch(doAuthentication())

2.4 我们可以像您提到的那样做 doAuthentication()(someDispatchFunction),但考虑一下这句话

If Redux Thunk middleware is enabled, any time you attempt to dispatch a function instead of an action object, the middleware will call that function with dispatch method itself as the first argument.

而且,您可以通过

找到有关 redux-thunk 的详细信息