我是 redux 的新手。我一次只能访问 1 个键值,而另一个不工作

I am new to redux. I am able to access only 1 key-value at a time and the other one is not working

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

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;

如果您的负载中有 { name: "bob" } formData: action.payload 将使 formData: { name: "bob" }

要保留旧的表单数据,您还需要对其进行解构。

formData: { ...state.formData, ...action.payload }

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;

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

1) 您可以克隆您的状态并在克隆的对象中进行必要的修改,然后 return 正如我在示例中所示

2) 或者,您可以探索 "update in react addons",它用于在保持状态不可变的同时更新所需的参数

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;