【发布时间】:2021-01-24 02:38:27
【问题描述】:
通过以下 Typescript React Redux 设置,在调度时,总是更新整个对象是常见的/最佳实践
dispatch(saveSettings({...state, ...color: 'blue' }))
或来自 SettingsInterface 的单个值
dispatch(saveSettings({color: 'blue' }))
为了更新单个值,动作创建者参数应该如何接受 SettingsInterface 的一个或多个键
const saveSettings = (settings: SettingsInterface) =>... // action creator argument is currently expecting all from the SettingsInterface
设置
const SAVE_SETTINGS = "SAVE_SETTINGS"
export interface SettingsInterface {
color: `red` | `blue`
preference: string
location: string
}
interface SaveSettingsInterface {
type: typeof SAVE_SETTINGS
settings: SettingsInterface
}
export type settingsActionTypes = SaveSettingsInterface
// action creator
export const saveSettings = (settings: SettingsInterface): settingsActionTypes => {
return {
type: SAVE_SETTINGS,
settings
}
}
//reducer
const settings = (state = settingsInitialState, action: settingsActionTypes): SettingsInterface => {
switch (action.type) {
case SAVE_SETTINGS_SUCCESS:
return { ...state, ...action.settings }
default:
return state
}
}
最后,在我更新“颜色”状态的 onChange 处理程序中;如何确保该值是 SettingsInterface 中指定的字符串文字 union('red' | 'blue') 的颜色之一?
// radio buttons onChangeHandler
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
let newColor = event.target.value
dispatch(saveSettings({ color: newColor }))
}
【问题讨论】:
标签: reactjs typescript redux