如何在 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>
);
}
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;
}
最佳答案
我不确定您是否可以使用 Axios.interceptors
因为在接收到数据的时间到渲染数据的时间之间总是会有延迟。但是,如果数据已经存在,我建议您 checkin 代码并根据此决定做什么。您可以根据您的数据更改外部 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>
);
}
如果您不确定是否会从服务器接收数据,您还可以在状态下创建一个新的 bool 变量,当您从 Axios 请求中获得响应时,该变量将从 false 变为 true,并使用它来更改 div 的 className .
关于javascript - 数据出现在网站上后禁用预加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64176927/