如何从Redux状态添加/删除项目

时间:2018-10-26 19:26:56

标签: reactjs redux

const initialState = {   usersById:[] }

值看起来像这样:

{
  "123" : { id : "123", name: "john", age: 234 },
  "234" : { id : "234", name: "smith", age: 343 }
}

如何编写我的reducer以添加和删除项目?

1 个答案:

答案 0 :(得分:0)

假设您有一个带有数据库的后端API ...

以下是动作:

export const CREATE_USER = 'CREATE_USER';

// Create
export function createUser(values, callback) {
  const request = axios
    .post(`${ROOT_URL}/users`, values)
    .then(() => callback());
  return {
    type: CREATE_USER,
    payload: request,
  };
}

// Delete
export const DELETE_USER = 'DELETE_USER';

export function deleteUser(id, callback) {
  const request = axios
    .delete(`${ROOT_URL}/users/${id}`)
    .then(() => callback());
  return {
    type: DELETE_USER,
    payload: id,
  };
}

// Get all users
export const FETCH_USERS = 'FETCH_USERS';

export function fetchUsers() {
  const request = axios.get(`${ROOT_URL}/users`);

  return {
    type: FETCH_USERS,
    payload: request,
  };
}

// Get one user by id
export const FETCH_USER = 'FETCH_USER';

export function fetchUser(id) {
  const request = axios.get(`${ROOT_URL}/users/${id}`);
  return {
    type: FETCH_USER,
    payload: request,
  };
}

这是减速器:

import _ from 'lodash';
import { FETCH_USERS, FETCH_USER, DELETE_USER } from '../actions/index';

export default (state = {}, action) => {
  switch (action.type) {
    case DELETE_USER:
      return _.omit(state, action.payload);
    case FETCH_USER:
      return { ...state, [action.payload.data.id]: action.payload.data };
    case FETCH_USERS:
      return _.mapKeys(action.payload.data, 'id');
    default:
      return state;
  }
};