反应路由器重定向

时间:2019-08-07 08:47:22

标签: reactjs axios

我有一个'getData'函数,该函数在组件安装时被调用。如果axios抛出错误,我希望将用户发送到登录页面。下面的代码给我以下错误:

  

未处理的拒绝(TypeError):无法读取以下内容的属性“ props”   未定义

在未注释的行上:

  

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);
    });
}

2 个答案:

答案 0 :(得分:2)

您必须保存对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

答案 1 :(得分:0)

或者您可以将ES6语法与箭头功能一起使用,以将其全局保留在函数中。

const getData = async (currentComponent) => {
      //this.props.history.push('/login');
    try {
      const response = await axios.get('******.php', {})

      console.log(response.data[0]);
      currentComponent.setState({tableData: response.data});
    } catch (e) {
      this.props.history.push('/login');
      console.log(e);
    }
}