reactjs - 反应路由器重定向
问题描述
我有一个函数“getData”,它在组件安装时被调用。如果 axios 抛出错误,我希望将用户发送到登录页面。下面的代码给了我以下错误:
未处理的拒绝(TypeError):无法读取未定义的属性“道具”
在未注释的行上:
this.props.history.push('/login');
有趣的是,如果我将该行移到 axios 函数之外,那么我会毫无问题地重定向(注释的 this.props.history.push('/login') 是)。
抛出 axios 错误时如何将用户带到登录页面?
getData(currentComponent) {
//this.props.history.push('/login');
axios.get('******.php', {
})
.then(function (response) {
console.log(response.data[0]);
currentComponent.setState({tableData: response.data});
})
.catch(function (error) {
this.props.history.push('/login');
console.log(error);
});
}
解决方案
您必须保存对的引用,this
因为它会在以下回调中发生变化axios.get
:
getData(currentComponent) {
const self = this;
//this.props.history.push('/login');
axios.get('******.php', {
})
.then(function (response) {
console.log(response.data[0]);
currentComponent.setState({tableData: response.data});
})
.catch(function (error) {
self.props.history.push('/login');
console.log(error);
});
}
另一种选择可能是使用箭头函数来定义getData
.
推荐阅读
- javascript - Javascript:警报函数忽略“if”语句并跳转到最后一个“else”
- bash - 在 bash 中通过 ssh 在远程服务器上运行命令的更快方法
- reactjs - 图像不显示反应
- python - 您可以使用 python/SQL/R 和 PowerBI 自动化 ETL 到仪表板管道吗?
- python - 使用 lambda 函数返回文件列表时 Snakemake 上的 InputFunction 错误
- html - 包含固定修复的居中 div
- mysql - 如何在mysql中过滤从晚上10点到14点但不晚于分钟的日期?
- python - 是否可以在不显式使用 python 中的索引的情况下引用列表项?
- xquery - xdmp:spawn-function() 替代方案
- javascript - 我如何在 javascript 中修复递归代码