首页 > 解决方案 > 为什么我的 reducer 将新对象添加到我的 redux 存储而不是更改当前对象值?

问题描述

我在使用 React-Redux 时遇到问题,我想更新商店中的特定值,但我在商店中获得了新对象。

我的动作类型:

export const SENDMESSAGE = "SENDMESSAGE";

我的动作创建者:

export const updateContactFormData = (payload) => ({
  type: SENDMESSAGE,
  payload: payload
})

我的初始状态:

export const formInitialData = {
  formShape: {...},
  formData: {...},
  formContactData: {
    name: '',
    email: '',
    text: ''
  }
}

我的减速机看起来像这样:

export default function formReducer(storeData, action) {

  switch(action.type) {

    case SENDMESSAGE:

      return {
        ...storeData,
        [storeData.formContactData]: action.payload,
      }

    default:
      return storeData || formInitialData
  }

}

现在我在我的商店中获得了新对象,正如 Redux 工具所示: 在此处输入图像描述

标签: reactjsreduxreact-redux

解决方案


您想要更新属性值,而不是使用以前的值作为名称来定义新属性。

return {
    ...storeData,
    formContactData: {...storeData.formContactData, ...action.payload},
  }

推荐阅读