javascript - 在 axios 响应做出反应后,如何有条件地重定向到页面?
问题描述
如果 axios api 为空或状态最初为空,我如何有条件地重定向到页面。在下面的代码中,我使用 axios 更新状态,并且用户信息在状态中可用,但代码继续调用http://userapi.com/login
in 循环。我想要实现的是,如果用户信息状态最初为空,则重定向到登录页面并进行身份验证。
class MyComponent extends React.Component {
constructor() {
super()
this.state = {
userinfo:{}
}
}
componentDidMount(){
axios.get('http://userapi.com/user')
.then(res => {
const userinfo = res.data;
this.setState({ userinfo });
})
.catch(err => {
console.log("Fetch error", err)
})
if (Object.keys(this.state.userinfo).length === 0) {
window.location = 'http://userapi.com/login';
}
}
render() {
return (
<React.Fragment>
<Header>Welcome</Header>
</React.Fragment>
)
}
}
我能够很好地重定向,但问题在于连续循环。即使用户信息正在存储重定向被调用(发生在循环中)
解决方案
Axios 返回Promise,因此具有if
以下条件的代码在更新块中状态的函数之前执行then
。因此,如果您需要在请求成功后检查更新的状态值,请将您的条件放在then
块内。
componentDidMount() {
axios
.get('http://userapi.com/user')
.then((res) => {
const userinfo = res.data;
this.setState({ userinfo }, () => {
if (Object.keys(this.state.userinfo).length === 0) {
window.location = 'http://userapi.com/login';
}
});
})
.catch((err) => {
console.log('Fetch error', err);
});
}
推荐阅读
- javascript - 执行全局安装的项目时出现 Windows 脚本错误
- amazon-web-services - AWS CloudFormation 模板在导入/导出值之间具有循环依赖关系
- spacy - 我可以使用 spaCy 命令行工具来训练包含其他实体类型的 NER 模型吗?
- html - 在其父容器外倾斜 div
- curl - cURL 读取外部变量
- c# - 统一冷却实施
- javascript - React 删除推送历史记录中的额外问号
- haskell - optparse-applicative 与自定义 monad
- node.js - 如何 console.log() 通过 mongoose 存储在 mongoDB 中的经度和纬度
- python - 如何在每次不打开 sqlite 连接的情况下运行功能