Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - 从axios请求捕获错误时重定向(Redirecting when catching an error from axios request)

I'm trying to redirect to an error page I made when I catch an error from an axiosRequest.(我试图重定向到我从axiosRequest捕获错误时创建的错误页面。)

So anyway, I got a .js full of methods like this:(因此,无论如何,我得到了一个充满以下方法的.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 }); } Then inside my .js pages I import that file and perform my requests.(然后,在我的.js页面中,导入该文件并执行我的请求。) When I get an error I do get the alert inside the catch in the previous code but I'm not able to redirect my page.(当我遇到错误时,我的确在上一个代码的警告中得到了警告,但我无法重定向页面。) How can I do this?(我怎样才能做到这一点?)   ask by Stackoverflowed translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can pass this.props to this function from component where you imported like(您可以从导入的组件this.props传递给此函数,例如)

getPublication(id,this.props); and your function(和你的功能) 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'); }); } Hope it will help(希望对你有帮助)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...