Moh*_* RN 4 action dispatch aurelia aurelia-store
我正在开发aurelia并使用aurelia-store进行应用程序状态管理.在从服务器加载数据时,我想更改isLoading字段true/false以在相关组件上显示掩码.所以我在我的州中定义了一个属性isLoading(例如).在加载操作中,我想首先将加载状态更改为true,并将数据检索为false.所以根据这个字段的值(isLoading)我想在组件上显示掩码.
我想要这样的东西:
export async function getRoles(state) {
try {
return Object.assign({}, state, { isRolesListLoading: {busy: true} });
const getRoles = await accountManagement.getRoles();
return Object.assign({}, state, { getRoles, isRolesListLoading: {busy: false} });
} catch (error) {
console.log('error getRoles "error": ', error);
}
}
Run Code Online (Sandbox Code Playgroud)
但正如我从aurelia文件中得知的那样,在一个动作中不允许进行两次状态更改.
我该怎么办?
我有一个想法,首先在这个动作中发出另一个动作,使isLoading成为真,然后完成工作.像这样的东西:
export async function getRoles(state) {
try {
desiredDispatch('goToLoadingState'); // fake code
const getRoles = await accountManagement.getRoles();
return Object.assign({}, state, { getRoles, isRolesListLoading: {busy: false} });
} catch (error) {
console.log('error getRoles "error": ', error);
}
}
Run Code Online (Sandbox Code Playgroud)
但我找不到一些关于如何在一个动作中发送另一个动作的文档.
有哪些可能的解决方案?
我试着把你的问题写成一个小样本,你可以在这里找到.
initialState是这样的:
initialState: {
roles: [],
isLoading: false
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它有一个角色数组,其中应该存储要加载的角色,以及一个isLoading有条件地显示加载指示符的布尔值.
现在我们已经设置了样本,让我们深入了解细节.
首先,从一个动作中远程加载数据是可行的,但应该小心.Aurelia Store的调度管道是一个异步队列.这意味着新操作最终会自动排队.现在,如果当前执行的操作需要很长时间才能解决,那么您可能会遇到滞后UI等问题,因为所有后续操作只会在以后更新.
其次,一个动作应该创造一个新的状态.你想要做的事实上包括3个动作.
因此,在链接示例中,我建议按以下方式执行此操作:
export class App {
...
async loadRoles() {
// Activate the loader, await the action so you don't start loading before the new state is actually set
await this.store.dispatch(setLoader, true);
// Local to the function start loading the roles, so you don't block the action queue
const roles = await loadRoles();
// once the data is available update the roles
await this.store.dispatch(updateRoles, roles);
// once that is set disable the loader
await this.store.dispatch(setLoader, false);
}
}
async function loadRoles() {
return new Promise(resolve => {
setTimeout(() => {
resolve(["User role", "Admin role", "Superuser role"]);
}, 1000);
});
}
function setLoader(state, isLoading) {
return Object.assign({}, state, { isLoading });
}
function updateRoles(state, roles) {
return Object.assign({}, state, { roles });
}
Run Code Online (Sandbox Code Playgroud)
现在这3个调度也可以减少到2个,因为设置数据加上禁用加载器可以一次性完成.关于动作的好处是你可以创建一个新的函数,通过编写旧的两个函数来完成它.
function updateRolesAndDisableLoader(state, roles) {
return Object.assign(
{},
updateRoles(state, roles),
setLoader(state, false)
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |