【发布时间】:2017-10-16 04:26:30
【问题描述】:
我对 React 很陌生,我似乎无法解决一个简单的问题。我正在实现 auth0 锁定小部件,并将其导入到我的“routes.js”中,如下所示:
routes.js:
import {requireAuth} from './js/helpers/AuthService.js';
我的 AuthService.js 没有构造函数,它只包含函数的声明,其中一些必须导出。片段:
AuthService.js:
const lock = new Auth0Lock(
client_id,
domain, {
auth: {
redirectUrl: `${window.location.origin}${LOGIN_ROUTE}`,
responseType: 'token id_token',
params: {
scope: 'openid email'
},
}
}
);
const events = new EventEmitter();
lock.on('authenticated', authResult => {
setAccessToken(authResult.accessToken);
lock.getUserInfo(authResult.accessToken, (error, profile) => {
if (error) { return setProfile({error}); }
setProfile(profile);
browserHistory.push(getNextPath());
clearNextPath();
});
});
export function login(options) {
lock.show(options);
return {
hide() {
lock.hide();
}
}
}
(etc.)
我唯一想要实现的是在加载其他所有内容之前通过 API 调用加载“client_id”和“domain”变量。所以基本上是这样的:
# fetch the config variables
fetch(url)
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(function(data) {
const client_id = data.client_id
const domain = data.domain
});
# Proceed with normal flow
const lock = new Auth0Lock(
client_id,
domain, {
auth: {
redirectUrl: `${window.location.origin}${LOGIN_ROUTE}`,
responseType: 'token id_token',
params: {
scope: 'openid email'
},
}
}
);
我遇到的问题是 fetch 是一个异步调用,因此其他代码不会等待它完成,这会在其余代码中触发错误(client_id 和 domain 未定义)。
我读过componentDidMount函数,但总是提到它可以用来延迟渲染。我没有什么要渲染的,我只想声明一些函数。为此,我只需要基于 API 调用设置一些常量变量。这不可能,但我似乎找不到一个好的解决方案。
【问题讨论】:
标签: reactjs react-native auth0