繁体   English   中英

使用React Hooks useReducer,如何有效地通过ID更新对象?

[英]Using React Hooks useReducer, how can I update an object by ID efficiently?

我有一个可以分叉的StackBlitz ,我找到了类似的答案,但是我在将其应用于示例时遇到了麻烦,我认为这是因为我有一组对象。

我的代码可以正常工作,但是它很冗长,我想让使用Redux的其他人更容易理解。

const initialState = [];
const todoReducer = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO': {
      return [...state, {
        id: state.length,
        name: action.name,
        complete: false
      }];
    }
    case 'TOGGLE_COMPLETE': {
      let left = state.filter((_, index) => index < action.index)
      let right = state.filter((_, index) => index > action.index)
      let completed = state.filter((_, index) => index == action.index)
      let updatedItem = {
        id: completed[0].id,
        name: completed[0].name,
        complete: !completed[0].complete
      }
      return [...left, updatedItem, ...right];
    }
    case 'CLEAR': {
      return initialState;
    }
    default: {
      return state;
    };
  }
}

我觉得答案类似于这个吗? 在React Redux Reducer中更新数组对象

在上面引用的答案中,他的对象具有state.posts如何更新我的示例,使其更类似于此示例?

如果我没有类似的状态对象,而又无法执行类似的操作,该如何定位待办事项:

state.todos.complete = false.

我想为“ COMPLETE”动作写一个更好的reduce。 我是否需要修改状态的结构,即是否需要将其作为一个空对象而不是对象数组?

只是map

case 'TOGGLE_COMPLETE': {
  return state.map((item, i) => i === action.index 
    ? {...item, complete: !item.complete}
    : item
  )
}

您可以有条件地更新“完成”而无需重复多次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM