【问题标题】:React router redirect反应路由器重定向
【发布时间】: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绑定

标签: reactjs axios


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    或者您可以使用带有箭头函数的 ES6 语法来将全局 this 保存在您的函数中。

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

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2017-10-22
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2018-12-25
      • 2021-09-29
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多