【发布时间】:2019-08-07 08:47:22
【问题描述】:
我有一个函数“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);
});
}
【问题讨论】:
-
试试把
getData改成箭头函数或者用this绑定