首页 > 解决方案 > 我是redux的新手。我一次只能访问一个键值,另一个不工作

问题描述

提交时只获取名称或任务,如何同时接收两个键值对

import * as actionTypes from './actions'
const initialState = {
    formData: {
        name: "",
        task: ""
    }
};

const reducer = (state = initialState, action) => {

    switch (action.type) {

        case 'SAVE_FORM_DATA':
            return {
                ...state,
                formData: {
                    formData: action.payload
                }

            }

        default:
            return state;
    }
}
export default reducer;

标签: javascriptreactjsreducers

解决方案


您可以通过 2 种方法做到这一点:

1)您可以克隆您的状态并在克隆的对象中进行必要的修改并返回它,如我在示例中所示

2)或者,您可以探索“更新反应插件”,用于更新所需的参数,同时保持状态不可变

import * as actionTypes from './actions'
const initialState = {
  formData: {
    name: "",
    task: ""
  }
};

const reducer = (state = initialState, action) => {
  switch (action.type) {

    case 'SAVE_FORM_DATA':
    let jasper = Object.assign({}, state); 
      return {
        jasper:action.payload
        }

      }

    default:
      return state;
  }
}
export default reducer; 

推荐阅读