基本上,我试图从轴响应中调用模型类。我想显示一个模式弹出而不是代码下方的警报。谁能帮助您从Axios拦截器函数调用模态类?预先感谢
import React, { Component} from 'react';
import axios from 'axios';
import Modals from '../components/modalAlerts/modalalerts'
const instance = axios.create({
baseURL: 'http://someurl',
timeout: 15000,
});
instance.defaults.headers.common['Authorization'] = //sequrity token will be here
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.interceptors.request.use(function (config) {
return config;
}, function (error) {
alert(error)
return Promise.reject(error);
});
instance.interceptors.response.use(function (config) {
return config;
}, function (error) {
console.log(error)
if(error.response){
if(error.response.status === 401||error.response.status === 403 ){
localStorage.clear()
alert(error.response.data.message)
}else if(error.response.status === 404){
console.log("404")
}else if(error.response.status === 400){
alert(error.response.data.message)
}else{
alert("something went wrong. Please try after sometime..!")
}
}else{
alert("server not found")
}
return Promise.reject(error);
});
export default instance;
答案 0 :(得分:1)
做下面的事情
为此您需要一个布尔标志。使用this.state
constructor(props){
super(props){
this.state = {
callModal: false,
errorMessage: ""
}
}
}
在下面的代码中,您需要将常规功能更改为箭头功能,以便访问this
内部
axios.interceptors.response.use(response => {
return response;
}, error => {
// set callModal flag to true using this.setState
this.setState({
callModal: true,
errorMessage: error
});
return Promise.reject(error);
});
或绑定函数,以便可以访问this
axios.interceptors.response.use(function (response) {
return response;
}.bind(this), function (error) {
// set callModal flag to true using this.setState
this.setState({
callModal: true,
errorMessage: error
});
return Promise.reject(error);
}.bind(this));
现在处于渲染调用模态类
render(){
const { callModal, errorMessage } = this.state;
return(){
<div>
{callModal && <ModalComponent errorMessage={errorMessage} />
</div>
}
}
要第二次使用相同的功能,您需要在用户使用回调方式单击模式中的“取消”按钮时将callModal设置为false