使用Lodash在Redux / React中添加和删除数据

时间:2016-07-12 23:29:15

标签: reactjs state redux lodash

我有一张带复选框的表格。当用户选中复选框时,id将被发送给动作创建者。

Component.js

handlePersonSelect({ id }, event) {
   const { selectPerson, deselectPerson } = this.props;
   event.target.checked ? selectPerson(id) : deselectPerson(id);
}

action.js

export function selectPerson(id) {
  console.log("selected")
  return {
    type: SELECT_PERSON,
     payload: id
  };
}

export function deselectPerson(id) {
  return {
    type: DESELECT_PERSON,
     payload: id
  };
}

我能够一直走到这一步,我迷失了: 这是违法的代码:

import { 
  SELECT_PERSON,
  DESELECT_PERSON,
  FETCH_PEOPLE
} from '../actions/types';


const INITIAL_STATE = {  people:[], selectedPeople:[]};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_PEOPLE:
        return {...state, people: action.payload.data};
    case SELECT_PERSON:
      return [action.payload, ...state ]; 
    case DESELECT_PERSON:
      return _.without({state, selectedPeople:action.payload});
  }
  return state;
}

selectedPeople状态应根据每种情况添加/减去id。截至目前,每当我取消选择身份证时,我的整个“人”表就会消失。

1 个答案:

答案 0 :(得分:1)

在所有情况下,您应该从reducer返回完整状态,所以:

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_PEOPLE:
      return {...state, people: action.payload.data};
    case SELECT_PERSON:
      return {...state, selectedPeople: [ ...state.selectedPeople, action.payload]}; 
    case DESELECT_PERSON:
      return {...state, selectedPeople: _.without(state.selectedPeople, action.payload)}; 
    default
      return state;
  }
}

另请注意,您没有采取DESELECT_PERSON操作,而是采取了2 SELECT_PERSON次操作。可能是一个错字。