Umb*_*bro 8 javascript reactjs axios
如何设置预加载器axios.interceptor以关闭数据在页面上的显示方式?此时,我可以看到数据已下载,预加载器关闭,当数据出现在页面上时,我可以看到跳转。预期效果:当网站上出现数据时禁用预加载器。
示例:https : //stackblitz.com/edit/react-ca6osn?file=src%2FApp.js
Axios.interceptors.request.use(function (config) {
// spinning start to show
// UPDATE: Add this code to show global loading indicator
document.body.classList.add('loading-indicator');
return config
}, function (error) {
return Promise.reject(error);
});
Axios.interceptors.response.use(function (response) {
// spinning hide
// UPDATE: Add this code to hide global loading indicator
document.body.classList.remove('loading-indicator');
return response;
}, function (error) {
return Promise.reject(error);
});
export default function App() {
const [values, setValues] = useState({
title: []
});
useEffect(() => {
loadProfile();
}, []);
const loadProfile = () => {
axios({
method: 'GET',
url: `https://jsonplaceholder.typicode.com/todos`,
})
.then(res => {
setValues({...values, title: res.data});
})
.catch(err => {
console.log('error', err.response.data);
})
}
return (
<div>
{values.title.map(data => (
<div style={{ border: "1px black solid" }}>
<p>{data.title}</p>
</div>
))}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
CSS
.loading-indicator:before {
content: '';
background: black;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 1000;
}
.loading-indicator:after {
content: 'Loading';
position: fixed;
width: 100%;
top: 50%;
left: 0;
z-index: 1001;
color:white;
text-align:center;
font-weight:bold;
font-size:1.5rem;
}
Run Code Online (Sandbox Code Playgroud)
我不确定您是否可以使用 来做到这一点,Axios.interceptors因为接收数据的时间与数据渲染的时间之间总是存在延迟。但是,我建议您检查代码中数据是否已存在,并根据此决定要做什么。您可以根据您的数据更改外部 div 的 className。
它应该是这样的:
export default function App() {
const [values, setValues] = useState({
title: []
});
useEffect(() => {
loadProfile();
}, []);
const loadProfile = () => {
axios({
method: 'GET',
url: `https://jsonplaceholder.typicode.com/todos`,
})
.then(res => {
setValues({...values, title: res.data});
})
.catch(err => {
console.log('error', err.response.data);
})
}
return (
<div className={values?.title?.length ? null : "loading-indicator"}>
{values.title.map(data => (
<div style={{ border: "1px black solid" }}>
<p>{data.title}</p>
</div>
))}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
如果您不确定是否会从服务器收到数据,您还可以在 state 中创建一个新的布尔变量,当您收到 Axios 请求的响应时,该变量将从 false 更改为 true,并使用它来更改 div 的 className 。
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |