如何在redux中更新对象中的特定值

Sai*_*das 1 reactjs redux react-redux

我的减速机:

   function updatePersonDetailsReducer (state = {
        updatePersonDetails: {
            name: "John",
            id: "3ery4",
            address: "somewhere on earth"
        }
    }, action) {
        switch (action.type) {
            case C.UPDATE_PERSON_DETAILS: {
                return {
                    ...state
                    ,updatePersonDetails :action.payload
                }
            }
            default : {}
        }
        return state
    }
Run Code Online (Sandbox Code Playgroud)

我在我的组件中这样调用,

this.props.dispatch(updatePersonDetails({name:Variant.objValue.name,id:Variant.objValue.Id}))
Run Code Online (Sandbox Code Playgroud)

但这似乎是创建一个新数组,而不是updatePersonDetails在reducer中覆盖当前数组()中的值。

sak*_*a73 5

你可以展开你的对象并像这样做。

 case C.UPDATE_PERSON_DETAILS: {
                return {
                    ...state,
                    updatePersonDetails : 
                    {...state.updatePersonDetails,...action.payload}
                }
            }
Run Code Online (Sandbox Code Playgroud)

这会将您的旧密钥保留在那里,并且只会更新新添加的密钥。