Reactjs 如何使用一个或多个Reducer状态值更新Typescript React Redux状态
设置了下面的Typescript React Redux后,在分派时,始终更新整个对象是否是常见/最佳做法Reactjs 如何使用一个或多个Reducer状态值更新Typescript React Redux状态,reactjs,typescript,redux,Reactjs,Typescript,Redux,设置了下面的Typescript React Redux后,在分派时,始终更新整个对象是否是常见/最佳做法 dispatch(saveSettings({...state, ...color: 'blue' })) 或设置界面中的单个值 dispatch(saveSettings({color: 'blue' })) const saveSettings = (settings: SettingsInterface) =>... // action creator argument i
dispatch(saveSettings({...state, ...color: 'blue' }))
或设置界面中的单个值
dispatch(saveSettings({color: 'blue' }))
const saveSettings = (settings: SettingsInterface) =>... // action creator argument is currently expecting all from the SettingsInterface
要更新单个值,action creator参数应如何接受SettingsInterface的一个或多个键
dispatch(saveSettings({color: 'blue' }))
const saveSettings = (settings: SettingsInterface) =>... // action creator argument is currently expecting all from the SettingsInterface
设置
最后,在onChange处理程序中,我正在更新“color”状态;如何确保该值是SettingsInterface中指定的字符串文字并集(“红色”|“蓝色”)的颜色之一
// radio buttons onChangeHandler
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
let newColor = event.target.value
dispatch(saveSettings({ color: newColor }))
}
//单选按钮onChangeHandler
const handleOnChange=(事件:React.ChangeEvent)=>{
让newColor=event.target.value
分派(保存设置({color:newColor}))
}
我正在打电话,请原谅我的格式错误
对于您的第一个问题:您应该在一个操作中传递最少的信息量。所以只是改变了属性。还原程序的任务是将更改与现有状态合并。所以用这个:
dispatch(saveSettings({color: 'blue' }))
要传递不完整的对象,请使用typescript实用程序type Partial
const saveSettings = (settings: Partial<SettingsInterface>)
但是event.target.value始终只是一个字符串,因此您必须使用“as”来声明它是更具体的类型颜色
dispatch(saveSettings({ color: newColor as Color }))
[const saveSettings=(settings:Partial)]表示操作创建者返回的操作不兼容,因为设置类型-setingsinterface现在包含未定义的。请在codesandbox上查看---