【发布时间】:2019-11-28 15:55:26
【问题描述】:
我对 Typescript React App 中 Redux 的类型保存实现有一些疑问。
我已经在 Reducer 上完成了设置和类型检查,还使用了 react-redux 中的 useTypedSelector。在这里,我在 Reducer 的案例语句中只有一件事是松散的类型检查,但这并不是那么成问题。
我的 Redux 商店设置:
// --------------------------------------- REDUX STORE ---------------------------------------
interface ITimePreset {
session: number;
break: number;
}
const UPDATE_TIMEPRESET = 'UPDATE_TIMEPRESET';
const INCREMENT_TIMEPRESET = 'INCREMENT_TIMEPRESET';
const DECREMENT_TIMEPRESET = 'DECREMENT_TIMEPRESET';
const BREAK = 'break';
const SESSION = 'session';
type Item = typeof BREAK | typeof SESSION;
interface IUpdateTimepresetAction {
type: typeof UPDATE_TIMEPRESET;
payload: {
value: number;
item: Item;
};
}
interface IIncrementTimepresetAction {
type: typeof INCREMENT_TIMEPRESET;
payload: Item;
}
interface IDecrementTimepresetAction {
type: typeof DECREMENT_TIMEPRESET;
payload: Item;
}
type TimePresetActionTypes = IUpdateTimepresetAction | IIncrementTimepresetAction | IDecrementTimepresetAction;
const initialState: ITimePreset = {
session: 25,
break: 5,
};
const timePresetReducer = (state: ITimePreset = initialState, action: TimePresetActionTypes): ITimePreset => {
switch (action.type) {
case UPDATE_TIMEPRESET:
return {
...state,
[action.payload.item]: action.payload.value,
};
case INCREMENT_TIMEPRESET:
return {
...state,
[action.payload]: state[action.payload] + 1,
};
case DECREMENT_TIMEPRESET:
return {
...state,
[action.payload]: state[action.payload] - 1,
};
default:
return state;
}
};
const rootReducer = combineReducers({
timePreset: timePresetReducer,
});
type RootState = ReturnType<typeof rootReducer>;
const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;
const store = createStore(rootReducer);
使用带有良好类型检查的 useTypedSelector 非常好:
const timePreset: ITimePreset = useTypedSelector(state => state.timePreset);
但是对于 useDispatch 我没有找到类型检查的解决方案:
const dispatch = useDispatch();
// This is the correct one:
dispatch({ type: DECREMENT_TIMEPRESET, payload: element });
// Wrong one with no error
dispatch({ type: 'Whaaat', payload: 9 });
有没有办法对 useDispatch 参数进行类型检查? 您对 Redux Store 的实现有其他建议吗(一些最佳实践)-> 这是我的第一个示例。
【问题讨论】:
标签: reactjs typescript redux react-redux