我正在编写一个React应用程序,我首先要确保在继续应用程序之前先设置两个JWT令牌(componentDidMount生命周期钩子)。我使用了回调函数来确保第二个函数正在等待第一个函数。但是由于某种原因,该值还不在我的本地存储中。我不能为此使用redux,因为我要提取的前两个调用是用户图像。
欢迎所有提示/建议。谢谢。
app.js
componentWillMount() {
function firstFunction(_callback){
acquireToken();
acquireGraphToken();
_callback();
}
function secondFunction(){
firstFunction(function() {
console.log('huzzah, I\'m done!');
});
}
secondFunction();
}
ADAL.JS(将处理我的令牌请求。)
import { AuthenticationContext, adalFetch } from 'react-adal';
const adalConfig = {
instance: 'https://login.microsoftonline.com/',
clientId: '*******',
extraQueryParameter: 'nux=1',
endpoints: {
graphApi: 'https://graph.microsoft.com',
oneApi: 'https://one365demo.onmicrosoft.com/b153b2*********-3f1d0cf658f5'
},
postLogoutRedirectUri: window.location.origin,
redirectUri: window.location.origin,
cacheLocation: 'localStorage'
};
export const authContext = new AuthenticationContext(adalConfig);
export const adalGraphFetch = (fetch, url, options) =>
adalFetch(authContext, adalConfig.endpoints.graphApi, fetch, url, options);
export const adalOneApiFetch = (fetch, url, options) =>
adalFetch(authContext, adalConfig.endpoints.oneApi, fetch, url, options);
export const getToken = () => {
return authContext.getCachedToken(authContext.config.clientId);
};
export const getGraphToken = () => {
return authContext.getCachedToken('https://graph.microsoft.com');
};
export const acquireGraphToken = () => {
authContext.acquireToken(adalConfig.endpoints.graphApi, (message, token, msg) => {
console.log('graph token', token);
return token;
})
return null;
}
export const acquireToken = () => {
authContext.acquireToken(adalConfig.endpoints.oneApi, (message, token, msg) => {
console.log('the token', token);
return token;
})
return null;
}
答案 0 :(得分:0)
您应该在该状态下创建一个值以跟踪您的初步功能完成情况。只需更改该值,然后正常加载组件即可。
例如
Perl
答案 1 :(得分:0)
render()
方法在很早的时候,之前 componentWillMount()
进行一次评估。然后,每次通过setState
方法更改组件状态时,原则上都会重新评估它。
我通常要做的是在初始化完成时标记组件的状态,并在render()
方法中检查该标记。在您的示例中:
componentWillMount() {
function firstFunction(_callback){
acquireToken();
acquireGraphToken();
_callback();
}
function secondFunction(){
firstFunction(function() {
console.log('huzzah, I\'m done!');
this.setState({dataIsReady: true})
});
}
secondFunction();
}
render() {
if (this.state.dataIsReady) {
// render the actual app
} else {
// render some "Loading ..." message
}
}
希望有帮助-卡洛斯(Carlos)