javascript - 加载屏幕并做出反应以改善用户体验
问题描述
我对加载数据方法有点困惑。所以我想在页面加载时显示加载屏幕,直到加载所有数据,我的方法是为此页面上的每个 fetch 方法设置加载状态。在这里,我使用redux
with thunk 来调度async
动作。
动作类型:
export const IS_LOADING_SKILLS = "IS_LOADING_SKILLS";
export const SET_SKILLS = "SET_SKILLS";
export const IS_LOADING_INTRO = "IS_LOADING_INTRO";
export const SET_INTRO = "SET_INTRO";
行动:
import { SET_SKILLS, SET_INTRO,IS_LOADING_INTRO,IS_LOADING_SKILLS} from "./actions-type"
export const fetchSkills = () => {
return (dispatch) => {
dispatch(isLoadingSkills(true));
await api.get(url)
.then(({ data }) => dispatch(setSkills(data)));
dispatch(isLoadingSkills(false));
}
}
export const fetchIntro = () => {
return (dispatch) => {
dispatch(isLoadingIntro(true));
await api.get(url)
.then(({ data }) => dispatch(setIntro(data)));
dispatch(isLoadingIntro(false));
}
}
const setSkills = (payload) => {
return {
type: SET_SKILLS,
payload: payload
}
}
const setIntro = (payload) => {
return {
type: SET_INTRO,
payload: payload
}
}
const isLoadingSkills = (payload)=>{
return{
type:IS_LOADING_SKILLS,
payload:payload
}
}
const isLoadingIntro = (payload)=>{
return{
type:IS_LOADING_INTRO,
payload:payload
}
}
状态:
const InitialState ={
loading:{
loadingIntro:false,
loadingSkills:false
},
data:{
intro:"",
skills:[],
}
}
现在,当每个 fetch data 方法的加载状态都变为 false 时,加载屏幕将消失。我想知道这是一个好方法还是更好的方法,请解释一下。谢谢你!
解决方案
这是一个很好的方法,但是您的代码有一些奇怪的部分。使用 async/await 或 .then/.catch 回调(不要忘记 .catch,您可以调度 setErrorMessage 操作左右)。
所以,有了你会做的承诺:
export const fetchSkills = () => {
return (dispatch) => {
dispatch(isLoadingSkills(true));
api.get(
.then(({ data }) => {
dispatch(setSkills(data)));
dispatch(isLoadingSkills(false));
})
.catch((error) => ...stuff)
}
}
export const fetchIntro = () => {
return (dispatch) => {
dispatch(isLoadingIntro(true));
api.get(url)
.then(({ data }) => {
dispatch(setIntro(data)));
dispatch(isLoadingIntro(false));
})
.catch((error) => ...stuff)
}
}
使用 async/await 你可以:
export const fetchSkills = () => {
return async (dispatch) => {
try {
dispatch(isLoadingSkills(true));
const { data } = await api.get(url)
dispatch(setSkills(data)));
dispatch(isLoadingSkills(false));
} catch(error) {
...stuff
}
}
}
export const fetchIntro = () => {
return async (dispatch) => {
try {
dispatch(isLoadingIntro(true));
const { data } = await api.get(url)
dispatch(setIntro(data)));
dispatch(isLoadingIntro(false));
} catch(error) {
...stuff
}
}
}
请记住,async/await 只是 Promise 的语法糖。而不是在promise上使用.then和.catch,您只需使用await作为异步定义函数(这允许您使用await并返回一个promise),您将需要try/catch来捕获在执行时可能发生的任何错误请求。
推荐阅读
- swift - MIKMIDI:在轨道上写入事件会产生警告
- python - 为什么我无法进入数据库?jacky@本地主机密码:NO
- google-apps-script - 需要帮助在谷歌表格中创建一个简单的宏来从数据创建多个图表
- javascript - 使用 express 和 node.js 在 ejs 模板中插入用户名
- java - 需要知道以下给定格式的数字格式
- c++ - 为什么我们可以这样做: Base *base = new Derived; 而我们不能做 Derived *derived = new Base?
- php - DomDocument 在样式元素中从文件中插入 CSS
- flutter - 在颤动中从 listView 导航页面
- excel - 将 vba 查找和替换限制为活动工作表
- php - CakePHP 4 自定义插件找不到类