reactjs - 如何针对 axios 响应验证 react-route
问题描述
如果方法返回 true,我想渲染组件isAuthenticated()
,一切正常,直到我从 axios 响应返回 true/false,似乎承诺被忽略了。我应该如何修改我的代码,我应该使用不同的方法吗?
这是我的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..'
);
}
其他一切都一样
解决方案
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; // <-- here you're returning this from your callback not from your isAuthenticated method
})
.catch(function (response) {
console.log("Klaida isAuthenticated PrivateRoute");
return false;
});
}
和
if (this.isAuthenticated) // <-- here you're not even calling your method
正确的方法是在组件中设置一些状态并根据您的响应设置您的状态,然后根据您的状态进行渲染
推荐阅读
- tensorflow - tensorflow keras embedding lstm
- ibm-cloud - 在 IBM Cloud 中没有默认资源组
- javascript - 从 Json 获取图像路径并分配给变量
- python - 在弹性搜索聚合器之间建立关系 - 嵌套分组
- mysql - Rails(utf-8 编码问题):活动记录错误地获取 msyqldb 数据
- c++ - 如何使用 C++ 检查 .text 文件中的字符序列?
- uwp - UWP 按钮在可见性变化时淡入,使用什么触发器?
- r - 如何用R删除括号内的数字?
- sql - 保持结果数据与插入的顺序相同
- amazon-web-services - 使用 javascript 将 AWS Lex 音频集成到网站