简体   繁体   English

我想给每个渲染的 todo 元素一个 id

[英]I want to give an id to every todo element that renders

function handleChange(event) {
    event.preventDefault()
    setNewItem(event.target.value)
}

In this function, I want to give every todo element a new and unique id.在这个 function 中,我想给每个 todo 元素一个新的唯一的 id。

function addTodo(event) {
    event.preventDefault()
    setNewItem({ id: 0 })
    setTodosList(prevList => [...prevList, newItem])
    setNewItem("");
    inputRef.current.focus()
    if (newItem === "") {
        alert("Plese Write an todo");
    }
}

function removeTodo() {
    // setTodosList(prevItems => prevItems.filter(item => item.id !== id))
}

const allTodos = todosList.map(item => (
    <li key={item}>
        {item}
        <i className="ri-delete-bin-line del" onClick={removeTodo}></i>
    </li>
));

Here all my code is running.我所有的代码都在这里运行。

<header>
    <img src={require('./images/todo.png')} alt="Todo-Logo" width="100" height="100" />
    <h1 className="title">My Todo App</h1>
</header>
<div className="container">
    <br />
    <form>
        <div className="input-btnFlex">
            <input
                type="text"
                placeholder="Write Your Todo "
                name="newItem"
                ref={inputRef}
                value={newItem}
                onChange={handleChange}
            />
            <button className="ri-add-circle-fill add-btn" onClick={addTodo}></button>
        </div>
    </form>
    <div>
        <ul>
            {allTodos}
        </ul>
    </div>
</div>

create a local variable id and every time you need a new id just increment the id.. Otherwise i would recommend assign Date.now() as the id as it will never have a duplicate value创建一个局部变量 id 并且每次您需要一个新的 id 时只需增加 id .. 否则我建议将 Date.now() 分配为 id因为它永远不会有重复的值

Other Method [Not Recommended] only use this if absolutely necessary : if you are using a list use the index of list as id..其他方法[不推荐] 仅在绝对必要时使用此方法:如果您使用列表,则使用列表的索引作为 id..

Here are some options that can be used for ids:以下是一些可用于 id 的选项:

  • Date/Time Stamp.日期/时间戳。
  • Any unique id generator for javascript like UUID javascript 的任何唯一 ID 生成器,例如 UUID
  • Create your own random id generator function using Math.random()使用 Math.random() 创建您自己的随机 id 生成器 function
  • You can create your own custom id string using index您可以使用索引创建自己的自定义 id 字符串

You can time stamp你可以时间戳

If a real human user is creating todo's one after another you can use a timestamp as an identifier since it will always be different each time and will stay the same no matter the order.如果一个真正的人类用户一个接一个地创建待办事项,您可以使用时间戳作为标识符,因为它每次总是不同的,并且无论顺序如何都将保持不变。

  • Always unique永远独一无二
  • Hard to guess很难猜
  • Always sequential总是顺序的
setNewItem({ id: Date.now().toString() })

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

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