我是 flutter 新手,试图观察像 React Native 这样处于减速器状态的变量“count”。我使我的 redux 和 hook 工作完美。屏幕上的变量计数发生变化,但如果我更改操作,则永远不会再次调用 useEffect(仅一次)事件。尝试了不同的方法但没有成功,并尝试将 StoreProvider.of(context).state.balanceState.count 直接放在 useEffect 的 dependentecis 中。如果我使用 useState 就应该像这样。
class StatePage extends HookWidget {
const StatePage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
int count = StoreProvider.of<AppState>(context).state.balanceState.count;
useEffect(() {
WidgetsBinding.instance.addPostFrameCallback((_) =>
StoreProvider.of<AppState>(context).dispatch(getBalanceThunk()));
}, [count]);
return Scaffold(
appBar: AppBar(
title: Text('ola'),
),
body: Center(
child: StoreConnector<AppState, BalanceState>(
converter: (store) => store.state.balanceState,
builder: (context, state) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (state.loading)
Column(
children: [
CircularProgressIndicator(),
SizedBox(
height: 30,
)
],
),
Text(state.message),
Text(count.toString()),
RaisedButton(
child: Text('Clicar'),
onPressed: (){
StoreProvider.of<AppState>(context).dispatch(SetCountAction(count++));
})
],
);
},
),
),
);
}
}
我的行动
abstract class BalanceAction {}
class BalanceStateAction extends BalanceAction {
final bool loading;
final bool error;
final String message;
BalanceStateAction(this.loading, this.error, this.message);
}
class SetBalanceAction extends BalanceAction {
final double value;
SetBalanceAction(this.value);
}
class SetCountAction extends BalanceAction {
final int count;
SetCountAction(this.count);
}
我的减速机
import 'package:flutter_red_test/redux/actions/balance_action.dart';
class BalanceState {
final bool loading;
final bool error;
final String message;
final double value;
final int count;
BalanceState({
this.loading = false,
this.count = 0,
this.error = false,
this.message = '',
this.value = null,
});
factory BalanceState.initialState(){
return BalanceState(
loading: false,
error: false,
message: '',
value: null,
count: 0,
);
}
BalanceState copy({bool loading, bool error, String message, double value, int count}){
return BalanceState(
loading: loading ?? this.loading,
error: error ?? this.error,
message: message ?? this.message,
value: value ?? this.value,
count: count ?? this.count,
);
}
}
BalanceState balanceReducer(BalanceState state, BalanceAction action){
if(action is BalanceStateAction){
return state.copy(
loading: action.loading,
message: action.message,
value: state.value,
error: action.error,
count: state.count,
);
}
if(action is SetBalanceAction){
return state.copy(
loading: false,
message: 'Seu saldo é de 20.000',
value: action.value,
count: state.count,
error: false,
);
}
if(action is SetCountAction){
return state.copy(
loading: false,
message: state.message,
value: state.value,
count: action.count,
error: false,
);
}
return state;
}