简体   繁体   English

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

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

I have a StackBlitz that you can fork, I found a similar answer but I'm having trouble applying it to my example, I think it's because I have an array of objects. 我有一个可以分叉的StackBlitz ,我找到了类似的答案,但是我在将其应用于示例时遇到了麻烦,我认为这是因为我有一组对象。

I have the code working but it's very verbose, and I would like something easier to read that others who use Redux will recognize. 我的代码可以正常工作,但是它很冗长,我想让使用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;
    };
  }
}

I feel like the answer is is similar to this one? 我觉得答案类似于这个吗? Update array object in React Redux reducer 在React Redux Reducer中更新数组对象

In the answer I cited above, his object has state.posts How can I update my example to be more like this one? 在上面引用的答案中,他的对象具有state.posts如何更新我的示例,使其更类似于此示例?

How can I target my Todos if I don't have a similar state object as I can't do something like: 如果我没有类似的状态对象,而又无法执行类似的操作,该如何定位待办事项:

state.todos.complete = false.

I want to write a better reducer for the 'COMPLETE' action. 我想为“ COMPLETE”动作写一个更好的reduce。 Do I need to modify how my state is structured, ie dopes it need to be an empty object instead of an array of objects? 我是否需要修改状态的结构,即是否需要将其作为一个空对象而不是对象数组?

Just map : 只是map

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

You can conditionally update "complete" without iterating multiple times. 您可以有条件地更新“完成”而无需重复多次。

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

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