为嵌套的对象数组创建reducer

时间:2018-06-05 09:54:50

标签: javascript reactjs redux reducers

我花了两天时间尝试创建reducer,它更改了属性toRecipe的布尔值,没有成功。这是嵌套的对象数组。我不能继续前进 这是数组的结构:

recipes: [ 
               { id: int, 
                 re: 'string',
                 c: [ 
                                  { id: int,
                                    co: 'string',
                                    toRecipe: false
                                  },
                                  {...}
                              ]
               },
               {...}
            ]

我创建了一个这样的缩减器:

case actionTypes.EDIT_BOOLEAN:
  return {
    ...state,
    recipes: {...state.recipes,
    [action.payload.idFromRecipe]: {...state.recipes[action.payload.idFromRecipe],
    c: {...state.recipes[action.payload.idFromRecipe].c,
    [action.payload.idFromComp]: {...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp], toRecipe: false}
  }
  }
  }
}

但是当我使用这个减速器时我有错误: TypeError:无法读取属性' c'未定义的

我在这里列出这个数组(粗体文字):

class RecipeList extends Component {

  render(){

    console.log(this.props.recipes.map(recipe=>recipe));
    let compons = this.props.recipes.map(recipe =>(
            <div key={recipe.id}>
            <h2>{recipe.re}</h2>
              <ul key={recipe.id}>
              {recipe.c.map(comp=> comp.toRecipe === true ?
                <li key={comp.id}>{comp.co}</li>
                : null
              )}
              </ul>
              <div>
                <form>
                 **{ recipe.c.map((comp, i)=>(
                  <div key={i}>
                <input
                  onChange={()=>this.props.editRecipes(comp.id,recipe.id)}
                  type="checkbox"
                  key={i}
                  checked={comp.toRecipe}
                />
                <label key={comp.id}>{comp.co}</label>

                </div>
              ))  }**
                </form>

              </div>
            </div>
      )
    );
    console.log(compons);
    return (
      <div>
        {compons}

      </div>
    )
  }
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

are you entirely sure that state.recipes.123.c exist? because it seems like it doesn't so it returns undefined so lane  

     ...state.recipes[action.payload.idFromRecipe].c,

所以基本上让我们举一个例子,你试图让嵌套对象工作。你的行为有效载荷是idFromRecipe =&#34; 123&#34;,

c: state.recipes[action.payload.idFromRecipe] ? {
   ...state.recipes[action.payload.idFromRecipe].c,
                [action.payload.idFromComp]: {
                    ...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp],
                    toRecipe: false
                }
} : {
                      ...state.recipes[action.payload.idFromRecipe].c[action.payload.idFromComp],
                    toRecipe: false
                }
}

将失败,因为您无法访问未定义的属性C. 为了让它像你那样工作,你需要检查它是否像

一样存在
spring-kafka

通常你应该避免这种结构,因为之后真的奇怪的逻辑和优化问题(因为你几乎每次都需要改变整个对象)。我的建议是用normalizr实际上标准化状态,例如并且它会更好地工作,并且不会有如上所述的疯狂逻辑。