反应:上下文挂钩,将对象推入数组

时间:2020-02-22 14:23:22

标签: reactjs typescript

我得到的错误是Cannot find name 'objectArray'.

interface StateInterface {
  objects: {
    objectArray: object[];
    selected: object;
  };
}

const InitialState: StateInterface = {
  objects: {
    objectArray: [],
    selected: {},
  },
};


const Reducer = (state: StateInterface, action: any) => {
  switch (action.type) {
    case 'SELECTED':
      return {
        ...state,
        objects: { ...state.objects, selected: action.value },
      };
    case 'ADD_OBJECT':
      return {
        ...state,
        objects: { ...state.objects, objectArray: objectArray.push(action.value )},
//                                                     ^---- Cannot find name 'objectArray'.ts(2304)
      };
    default:
      return state;
  }
};

我也尝试过

objects: { ...state.objects, objectArray:  ...action.value )},

1 个答案:

答案 0 :(得分:2)

在那时,只有状态对象在作用域内(作为reducer的参数提供),请在出现错误时尝试将objectArray切换为state.objectArray

但是,您还需要不可变地附加值以使其正确(归约化规则),因此您需要使整行类似:

objects: { ...state.objects, objectArray: [...state.objectArray, action.value]},

要使用旧值和要添加的新值创建新数组。