繁体   English   中英

当使用 Date.now() 制作密钥时,我不确定如何访问和比较对象

[英]I'm not sure how to access and compare an object when keys are made using Date.now()

我对编码很useReducer() ,我目前正在 React 中练习useReducer()钩子来管理一个简单的待办事项应用程序中的一些状态。 我在尝试实施 TOGGLE_TODO 操作时遇到了问题。 我在使用数组之前已经完成了它,但是由于我可能会使用很多对象,所以我试图弄清楚为什么我不能正确地做到这一点。 我会说我是通过失败来学习的,但我所学习的只是如何关掉电脑然后走开!

每次切换时,我都使用扩展运算符传递状态,我已经在所有项目中尝试了它,我已经注销了keyaction.payload以确保我得到匹配(它有效当我做一个简单的匹配警报时)。

我知道切换还不是切换,我只是想简单地complete成为true

我已经尝试了很多方法来返回状态,我在语句的开头添加了 return,并且在此过程中遇到了一些奇怪的错误。如前所述,现在这是非常简单的状态,但它会在我正在进行的另一个项目中变得更复杂,所以 useState 变得非常混乱。

对我在这里做错的任何帮助将不胜感激。

const initialAppState = {
  isOpen: true,
  todos: {}
};

export const ACTIONS = {
  TOGGLE_MODAL: "toggle-modal",
  ADD_TODO: "add-todo",
  TOGGLE_TODO: "toggle-todo"
};

const reducer = (state, action) => {
  // switch statement for actions
  switch (action.type) {
    case ACTIONS.TOGGLE_MODAL:
      return { ...state, isOpen: !state.isOpen };
    case ACTIONS.ADD_TODO:
      return {
        ...state,
        todos: {
          ...state.todos,
          // Object is created with Unix code as the key
          [Date.now()]: {
            todo: action.payload.todo,
            complete: false
          }
        }
      };
    case ACTIONS.TOGGLE_TODO:
      // Comparing the key and the action payload. If they match, it should set complete to 'true'. This will be updated to a toggle when working. 
      Object.keys(state.todos).map((key) => {
        if (key === action.payload) {
          return {
            ...state,
            todos: { ...state.todos, [key]: { complete: true } }
          };
        }
        return state;
      });
    default:
      throw new Error("Nope. not working");
  }
};

在渲染中,我将key作为id传递,以便它可以与有效负载一起返回。 这是组件的dispatch函数...

const Todo = ({ id, value, dispatch }) => {
  return (
    <div className="todo">
      <h1>{`Todo: ${value.todo}`}</h1>
      <p>Done? {`${value.complete}`}</p>
      <button
        onClick={() =>
          dispatch({
            type: ACTIONS.TOGGLE_TODO,
            payload: id
          })
        }
      >
        Mark as Done
      </button>
    </div>
  );
};

并且渲染使用Object.entries一切正常。 有时我会遇到错误,或者最初的todo会消失,所以我知道状态没有被正确更新。

这里也是CodeSandbox 上代码 如果我让它工作,我会在这里更新,但我已经被困在这里几天了。 :-(

你快到了,用 Date.now() 索引你的项目是个好主意!
TOGGLE_TODO 案例中只有几个问题:

  • 你的reducer应该总是返回一个状态,你的return语句应该在case的末尾,但是你把它和map的函数放在一起
  • 您的 reducer 应该计算一个新状态,而不是改变当前状态。 所以你必须用完整的属性创建一个新的 todo 对象。

这是它的过程:

    case ACTIONS.TOGGLE_TODO:
      const newTodos = Object.keys(state.todos).map((key) => {
        if (key === action.payload) {
          return { ...state.todos[key], complete: true } // create a new todo item
        }
        else {
          return state.todos[key]; // keep the existing item
        }
      });
      return {...state, todos: newTodos};

暂无
暂无

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

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