【问题标题】:How to Update Typescript React Redux State With One or More Reducer State Values如何使用一个或多个 Reducer 状态值更新 Typescript React Redux 状态
【发布时间】: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


    【解决方案1】:

    我在用手机,所以请原谅我的错误格式。

    对于您的第一个问题:您应该在操作中传递最少的信息。所以只是改变了属性。 reducer 的工作是将更改与现有状态合并。所以用这个:

    dispatch(saveSettings({color: 'blue' }))
    

    要传递不完整的对象,请使用 typescript 实用程序类型 Partial。

    const saveSettings = (settings: Partial<SettingsInterface>)
    

    您可以通过使用获得可接受的颜色值的并集

    type Color = SettingsInterface[‘color’]
    

    但 event.target.value 永远只是一个字符串,所以你必须使用“as”来断言它是更具体的颜色类型。

    dispatch(saveSettings({ color: newColor as Color }))
    

    【讨论】:

    • [const saveSettings = (settings: Partial)] 意味着操作创建者返回的操作不兼容,因为设置类型 -SettingsInterface 现在包含未定义。请在codesandbox上查看---codesandbox.io/s/36w5n
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 2019-07-28
    • 2018-11-15
    • 2019-02-25
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    相关资源
    最近更新 更多