通过Redux的Reducer更新列表

Ale*_*dro 4 reducers reactjs redux react-redux

我正在React做一个小的食谱清单用于学习目的(因为我是新手).

我能够从列表中找出如何添加和删除配方.但是我很难从列表中编辑配方(App的状态).

以下是Redux的文档:

因为我们想要在不诉诸突变的情况下更新数组中的特定项,我们必须使用与索引处的项目相同的项创建一个新数组.

我很难在修改自己选择的数组时选择数组中的特定项.

这是我的动作文件:

SRC /行动

export const RECIPE_ADD = 'RECIPE_ADD';
export const RECIPE_EDIT = 'RECIPE_EDIT';
export const RECIPE_DELETE = 'RECIPE_DELETE';
export function addRecipe(recipe) {
  return {
    type: RECIPE_ADD,
    payload: recipe
  }
}
export function editRecipe(recipe) {
  return {
    type: RECIPE_EDIT,
    payload: recipe
  }
}
export function deleteRecipe(recipe) {
  return {
    type: RECIPE_DELETE,
    payload: recipe
  }
}
Run Code Online (Sandbox Code Playgroud)

SRC /减速器/ reducer_recipe

import { RECIPE_ADD } from '../actions/index';
import { RECIPE_DELETE } from '../actions/index';
import { RECIPE_EDIT } from '../actions/index'

const defaultList = [
  { recipe: 'Pizza', ingredients: ['tomato-sauce','cheese','peperoni'] },
  { recipe: 'Pie', ingredients: ['dough','cherry'] },
  { recipe: 'Curry', ingredients: ['rice','sauce','carrots'] },
];

export default function(state = defaultList, action){
  switch (action.type) {
    case RECIPE_ADD:
      return [
        { recipe: action.payload[0], ingredients: action.payload[1] },
        ...state
      ];
    case RECIPE_DELETE:
    let index = state.map(x => x.recipe).indexOf(action.payload.recipe)
      return (
        state.slice(0,index).concat(state.slice(index + 1))
      )
    case RECIPE_EDIT:
    console.log(action.payload)
    // action.payload is the updated selected recipe
      return (
        state
      )
  }
  return state;
}
Run Code Online (Sandbox Code Playgroud)

我怀疑我需要在动作中添加一个id来区分它与数组列表?

bns*_*d55 5

您应该在defaultList中为对象添加一个id:

const defaultList = [
  { id: 1, recipe: 'Pizza', ingredients: ['tomato-sauce','cheese','peperoni'] },
  { id: 2, recipe: 'Pie', ingredients: ['dough','cherry'] },
  { id: 3, recipe: 'Curry', ingredients: ['rice','sauce','carrots'] },
];
Run Code Online (Sandbox Code Playgroud)

然后更新你的食谱:

    case RECIPE_EDIT:
      return state.map((recipe)=> {
        if( recipe.id == action.payload.id ) {
          return action.payload
        } else {
          return recipe;
        }
      });
Run Code Online (Sandbox Code Playgroud)

只有当你确定并且都是Integer时,才应该使用if ===而不是==on条件.recipe.idaction.payload.id