【发布时间】:2019-01-14 04:42:30
【问题描述】:
我有以下代码,我想从 url 获取访问令牌并将其放入会话存储中,并让我的子组件使用访问令牌来获取我的信息。但是,当组件第一次加载时,它似乎没有找到访问令牌,但如果我再次刷新它就可以工作。为了解决这个问题,我想到了使用 async / await 以便在未设置会话令牌之前它不会进一步重定向到子组件,但这似乎并没有等待设置令牌。不知道我做错了什么?
class App extends React.Component {
constructor(props){
super(props);
this.processToken();
}
componentDidMount() {
const { user } = this.props;
const { accessToken } = user;
// expecting access token to print here by it is not
console.log('user token : ', accessToken);
}
processToken = async () => {
try {
const params = querySearch(this.props.location.search);
if('accessToken' in params){
await new Promise((resolve,reject) => {
this.setOrderContext(params);
resolve();
} );
this.props.history.push(`/myinfo`);
}
} catch(ex) {
console.log(ex);
}
}
setOrderContext (params){
//this action calls a reducer and put the token in session storage
this.props.userActions.processUserToken({data: {accessToken:params.accessToken}});
}
render() {
return (
<Switch>
//myinfo component needs accessToken to retrieve my info
<Route path="/myInfo" component={InofUI.App} />
</Switch>
);
}
【问题讨论】:
标签: reactjs promise async-await