jus*_*ron 9 javascript typescript reactjs
我是 JS、React 和 TypeScript 的新手。我做了一个添加待办事项列表的教程。为了进行一些练习,我决定添加删除按钮和“删除最后一项”按钮。
\n删除完整列表效果很好(我为自己感到骄傲,哈!)但是“删除最后一项”不起作用,我尝试了不同的事情(例如只是todos.pop()
)。
\nfunction App() {\n const [todos, setTodos] = useState([])\n const [input, setInput] = useState("")\n\n // prevents default, adds input to "todos" array and removes the input from form\n const addTodo = (e) => {\n e.preventDefault()\n\n setTodos([...todos, input])\n setInput("")\n }\n\n // deletes the todo-list\n const clearTodo = (e) => {\n e.preventDefault()\n\n setTodos([])\n }\n\n // deletes the last entry from the todo-list\n const clearLastTodo = (e) => {\n e.preventDefault()\n\n setTodos(todos.pop())\n }\n\n return (\n <div className="App">\n <h1>ToDo Liste</h1>\n <form>\n <input \n value={input} \n onChange={(e) => setInput(e.target.value)} \n type="text" \n />\n <button type="submit" onClick={addTodo}>\n Hinzuf\xc3\xbcgen\n </button>\n </form>\n\n <div>\n <h2>Bisherige ToDo Liste:</h2>\n <ul>\n {todos.map((todo) => (\n <li>{todo}</li>\n ))}\n </ul>\n </div>\n\n <div>\n <form action="submit">\n <button type="submit" onClick={clearLastTodo}>\n Letzten Eintrag l\xc3\xb6schen\n </button>\n <button type="submit" onClick={clearTodo}>\n Liste l\xc3\xb6schen\n </button>\n </form>\n </div>\n </div>\n );\n}\n\nexport default App;\n
Run Code Online (Sandbox Code Playgroud)\n我错过了什么吗(显然我错过了,否则它会起作用)?但什么?:D
\n先感谢您!
\nIti*_*tik 15
您的问题有 3 种可能的解决方案。
解决方案 1: 将数组从第一个元素切片到 -1(最后一个元素之前的 1)元素。
setTodos(todos.slice(0, -1)));
Run Code Online (Sandbox Code Playgroud)
或者
setTodos((previousArr) => (previousArr.slice(0, -1)));
Run Code Online (Sandbox Code Playgroud)
方案二: 创建一个复制数组,将其与-1的值进行拼接。然后将数组从第一个元素设置到-1 元素。
const copyArr = [...todos];
copyArr.splice(-1);
setTodos(copyArr);
Run Code Online (Sandbox Code Playgroud)
解决方案 3:
使用 创建一个副本列表...
,弹出该副本并将数组的新值设置为该副本。
const copyArr = [...todos];
copyArr.pop();
setTodos(copyArr);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9100 次 |
最近记录: |