name: 异步redux-actions-无状态改变 description: 创建AsyncRedux(Flutter)操作,从reduce()返回null以不改变状态。此类操作仍可执行副作用、调度其他操作或什么都不做。
不改变状态的操作
在AsyncRedux中,从reducers返回新状态是可选的。当您不需要修改应用程序状态时,返回null以保持当前状态不变。
基本模式
当不需要修改状态时,从reduce()返回null:
class MyAction extends ReduxAction<AppState> {
AppState? reduce() {
// 在这里执行副作用
return null; // 状态保持不变
}
}
条件状态更新
仅在满足某些条件时更新状态:
class GetAmount extends ReduxAction<AppState> {
Future<AppState?> reduce() async {
int amount = await getAmount();
if (amount == 0)
return null; // 不需要改变
else
return state.copy(counter: state.counter + amount);
}
}
协调其他操作
调度其他操作但不直接修改状态的操作:
class InitAction extends ReduxAction<AppState> {
AppState? reduce() {
dispatch(ReadDatabaseAction());
dispatch(StartTimersAction());
dispatch(TurnOnListenersAction());
return null; // 此操作本身不改变状态
}
}
触发外部服务
调用外部服务而不修改应用状态:
class SendNotification extends ReduxAction<AppState> {
final String message;
SendNotification(this.message);
Future<AppState?> reduce() async {
await notificationService.send(message);
return null;
}
}
导航操作
作为副作用触发导航:
class GoToSettings extends ReduxAction<AppState> {
AppState? reduce() {
dispatch(NavigateAction.pushNamed('/settings'));
return null;
}
}
关键点
- 确实返回新状态的操作也可以执行副作用和调度其他操作。
- 返回类型很重要:对于同步操作使用
AppState?,对于异步操作使用Future<AppState?>。 - null表示无改变:存储保持其当前状态。
参考文献
文档URL:
- https://asyncredux.com/flutter/basics/changing-state-is-optional
- https://asyncredux.com/flutter/basics/actions-and-reducers
- https://asyncredux.com/flutter/basics/sync-actions
- https://asyncredux.com/flutter/basics/async-actions
- https://asyncredux.com/flutter/advanced-actions/redux-action
- https://asyncredux.com/flutter/advanced-actions/before-and-after-the-reducer