首页 > 解决方案 > 反应路由器重定向

问题描述

我有一个函数“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);
    });
}

标签: reactjsaxios

解决方案


您必须保存对的引用,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.


推荐阅读