从axios请求捕获错误时重定向

时间:2019-11-29 15:36:04

标签: javascript reactjs axios

我试图重定向到我从axiosRequest捕获错误时创建的错误页面。 所以无论如何,我的.js充满了这样的方法:

export const getPublication = async (id) => {
    const idJSON = {"id": id,}
    return await axios({
        method: 'post',
        url: 'users/getPublicationByID',
        data: idJSON
      })
      .then(function (response) {
          return response.data
      })
      .catch(function (error) {
          alert("Hello: " + error); //this alert shows up correctly
          this.context.history.replace('/error') //this isnt working
      });
}

然后在我的.js页面内,导入该文件并执行我的请求。 当我遇到错误时,我的确在上一个代码的警告中得到了警告,但我无法重定向页面。我该怎么办?

4 个答案:

答案 0 :(得分:2)

您可以从导入的组件中将this.props传递给此函数

getPublication(id,this.props);

和您的功能

export const getPublication = async (id,props) => {
    const idJSON = {"id": id,}
    return await axios({
        method: 'post',
        url: 'users/getPublicationByID',
        data: idJSON
      })
      .then(function (response) {
          return response.data
      })
      .catch(function (error) {
          alert("Hello: " + error); //this alert shows up correctly
          props.history.push('/path');          
      });
}

希望这会有所帮助

答案 1 :(得分:1)

您正在使用箭头功能,因此 <input name="date" type="date" value="<?php echo date('F d, Y'); ?>" /> 在此上下文中是一个窗口或未定义(如果您处于JS严格模式下”。您可能需要将历史记录作为参数传递给{{1 }}函数。另一种解决方案(如果您确定要在其上调用函数的函数或类具有有效的history.replace)是将arrow函数更改为常规函数。在这种情况下,这将引用作用域函数/类。

答案 2 :(得分:1)

您可以尝试以下方法:

 .catch(function (error) {
          alert("Hello: " + error);
          window.location.replace("/error")
  });

如果您不想刷新,可以使用react-router中的history.push

答案 3 :(得分:0)

For Each w In ThisWorkbook.Sheets(Array("Sheet1", "Sheet2"))
  w.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, _
 IgnorePrintAreas:=False, OpenAfterPublish:=True
Next w

}

以及在渲染块中:

export const getPublication = async (id) => {
const idJSON = {"id": id,}
return await axios({
    method: 'post',
    url: 'users/getPublicationByID',
    data: idJSON
  })
  .then(function (response) {
      return response.data
  })
  .catch(function (error) {
      alert("Hello: " + error); //this alert shows up correctly
      this.setstate({dataError:true})
  });
相关问题