【问题标题】:Changing the indexes of items of array on filtering out that array in React在 React 中过滤掉数组时更改数组项的索引
【发布时间】:2021-11-02 18:09:24
【问题描述】:
const [todoList, setTodoList] = useState([{ id: 0, name: 'No active Todos' }]) // Defined in another file. Imported in its child component as allTodos and setTodoList for changing state using props.

const Todos = (props) => {

const setTodoList = (todoId) => {
        if (props.allTodos.length === 1) {
            props.setTodoList([{ id: 0, name: 'No active Todos' }])
        }

        else {
            props.setTodoList(props.allTodos.filter(
                todo => todo.id !== todoId
            ))
        }
    }

return (

<div id="todos_container">
{
  props.allTodos.map((prev) => {
    return (
       <div id="item_container">
         <button type='button' className='check_button' onClick={() => setTodoList(prev.id)} />
         <div>{props.allTodos.name}</div>
       </div>
    )
  })
}
</div>
}

现在,假设todoList 有三个项目,例如: [ {id: 1, name: "..."}, {id: 2, name: "..."}, {id: 3, name: "..."} ]

如果我单击从映射数组返回的第二个项目/元素,那么第二个对象将从 setTodoList 中删除,它会像:
[ {id: 1, name: "..."}, {id: 3, name: "..."} ]

所以,我想要的是 id 将自身更改为连续数字,例如: [ {id: 1, name: "..."}, {id: 2, name: "..."} ] 而不是 [ {id: 1, name: "..."}, {id: 3, name: "..."} ]

【问题讨论】:

    标签: reactjs react-functional-component


    【解决方案1】:
    1. 不推荐在处理数组时使用索引作为唯一标识符。

    2. 您可以使用对象来存储数据,“id”作为唯一标识符,对应的对象作为值。

      const [todoList, setToDoList] = useState({
          1 : {id:1, name:''},
          2 : {id:2, name:''}
      })
      
    3. 将 id 作为参数传递给 setToDoList。使用这种方法可以轻松修改状态 todoList,因为我们将使用唯一的键访问元素。

    【讨论】:

    • 我没听懂。我的意思是它将如何帮助我将 id 更改为连续数字?可以举个例子详细说明一下吗?
    • 如果 todoLists 按照上面的建议存储,您可以在呈现 todLists 时将“id”作为键并将相同的“id”作为参数传递给 onClick 处理程序。因为我们正在处理对象,您可以删除键等于“id”的元素。如果那是您在 setToDoList 中所做的事情。如果我的理解不正确,请帮助我理解您的方法。
    【解决方案2】:

    可能最简单的方法是在每次修改对象数组时重新生成它。您可以考虑将事实来源存储为数字到字符串的映射 - 即

    const todos = new Map();
    todos.set(1, 'todo1');
    todos.set(2, 'todo2');
    // etc
    

    然后在你的子组件中创建一个数组来映射:

    const list = useMemo(() => {
      let arr;
      props.todos.forEach((val, key) => {
        arr.push({ id: key, name: val });
      });
      return arr;
    }, [props.todos.values()]);
    
    return (
      // todo will have the type: { id: number; name: string; }
      {list.map(todo => // JSX here)}
    )
    
    

    在删除函数中,只需调用props.todos.delete(id)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      相关资源
      最近更新 更多