【发布时间】:2019-07-27 10:31:34
【问题描述】:
如果isAuthenticated() 方法返回true,我想渲染组件,一切正常,直到我从axios 响应返回true/false,似乎promise 被忽略了。我应该如何修改我的代码,我应该使用不同的方法吗?
这是我的isAuthenticate():
isAuthenticated = () =>{
const cookie = new Cookie();
axios.get("/api/check", {
headers : {
'Authorization' : 'Bearer ' + cookie.get('access_token')
}})
.then(function (response) {
console.log(response.data.auth"); //returns actuall value
return response.data.auth; // completely ignored
})
.catch(function (response) {
console.log("Klaida isAuthenticated PrivateRoute");
return false;
});
};
这是我的render()
render() {
const {component: Component, ...rest} = this.props;
const renderRoute = props => {
const to = {
pathname: '/login',
state: {from: props.location}
};
if (this.isAuthenticated) {
return (
<Component {...props} />
);
} else {
return (
<Redirect to={to}/>
);
}
};
return (
<Route {...rest} render={renderRoute}/>
);
}
编辑
所以我将我的逻辑从isAuthenticated() 移动到componentWillMount() 方法,并添加了状态元素以了解何时完成提取,如下所示:
componentWillMount() {
const cookie = new Cookie();
let self =this;
axios.get("/api/check", {
headers : {
'Authorization' : 'Bearer ' + cookie.get('access_token')
}})
.then(function (response) {
self.setState({
auth: response.data.auth,
res: true
});
console.log(self.state.auth)
})
.catch(function (response) {
console.log("Klaida isAuthenticated PrivateRoute");
});
}
我在等待响应时做了条件渲染:
if(this.state.res){
return (
<Route {...rest} render={renderRoute}/>
);
}else{
return (
'loading..'
);
}
其他都一样
【问题讨论】: