【发布时间】:2017-08-12 01:29:39
【问题描述】:
所以,我正在为一个宠物项目探索 auth0。在他们的文档和网站提供的分步指南的帮助下,我能够为我的应用程序配置身份验证。下一步是从 auth0 获取配置文件,它也成功了,但问题是当我必须使用配置文件 id 从本地数据库中获取用户数据时。由于getUserProfile() 是异步的,因此获取配置文件的推荐方法是在将其设置为本地存储并在<Home/> 组件中捕获它之后,在帮助程序类中触发一个事件发射器。我一直在尝试不同的解决方法来避免它,但没有任何效果。我整天都在尝试这样做。请帮忙。我这里附上相关代码。
AuthService 帮助类
import Auth0Lock from 'auth0-lock'
import {
isTokenExpired
}
from './jwtHelper'
import {
EventEmitter
}
from 'events'
export default class AuthService extends EventEmitter {
constructor(clientId, domain) {
// Configure Auth0
this.lock = new Auth0Lock(clientId, domain, {
autoclose: true,
theme: {
logo: logo,
primaryColor: "#337ab7"
},
languageDictionary: {
title: "PHA"
},
auth: {
redirect: false,
responseType: 'token'
}
})
// Add callback for lock `authenticated` event
this.lock.on('authenticated', this._doAuthentication.bind(this))
// binds login functions to keep this context
this.login = this.login.bind(this)
}
_doAuthentication(authResult) {
// Saves the user token
this.setToken(authResult.idToken)
// navigate to the home route
browserHistory.replace('/home')
this.lock.getUserInfo(authResult.accessToken, function(error, profile) {
if (error) {
console.log('Error loading the Profile - AuthService', error)
} else {
console.log("got", profile.name);
localStorage.setItem('profile', JSON.stringify(profile))
this.emit('profile_updated', profile)
}
})
}
getProfile() {
// Retrieves the profile data from local storage
const profile = localStorage.getItem('profile')
return profile ? JSON.parse(localStorage.profile) : {}
}
}
我还在控制台中收到一个错误,即从不使用 EventsEmitter。我做错了什么。
这是我的 Home 组件。
class Homecontent extends React.Component{
static contextTypes = {
router : React.PropTypes.object
}
static propTypes = {
auth: React.PropTypes.instanceOf(AuthService)
}
constructor(props,context){
super(props);
this.state={
profile: {},
user : "",
avatar: placeholder,
family: [],
nextappt: "0",
diagnosis: [],
medication:[],
advise:[],
tests:[],
mainchartdata:[],
piechartdata:[],
filtertext: "",
filtersource:"",
}
this.filtercallback= this.filtercallback.bind(this);
props.auth.on('profile_updated', (newProfile) => {
console.log("updated profile");
this.setState({profile: newProfile})
})
}
包含以下代码时,应用程序不会运行。
props.auth.on('profile_updated', (newProfile) => {
this.setState({profile: newProfile})
})
这显然是 EventsEmitter 或 this.emit() 的问题。
请帮忙。 }`
【问题讨论】:
-
第一个错误不是很明显吗?您永远不会在 AuthService 帮助程序中使用 EventEmitter。只需对 EventEmitter 进行文本搜索,您所做的就是导入。请参阅 docs 中的初始化事件发射器
-
啊。又出问题了。现在我从 EventEmitter 扩展了 AuthService 类。尽管如此,事件发射器仍然不起作用。我错过了什么?
-
您仍然遇到同样的错误? EventsEmitter 没用过?
-
没有。这就解决了。我现在扩展了 EventEmitter。查看更新的代码。问题是事件发射器没有触发事件(或)监听。我不明白是什么原因造成的。
-
你能把代码放在你传递 auth prop 到 Homecontent 组件的地方吗?你能看到 Homecontent 组件中的 console.log(auth) 的结果吗?虽然,由于您已将检查放入 propTypes,但如果您没有传递正确的道具,它应该会失败。
标签: reactjs auth0 eventemitter