array.splice(index, 1) 返回已删除项目的数组

我正在学习 React hooks,我只是尝试执行一个简单的函数来从列表中删除该项目。为此,我使用 find、indexOf 和 splice。


在 onClick 函数中,我在 array.splice(indexOf, 1) 中使用 indexOf,但它仅返回列表中的项目。所有内容都会重新渲染并执行其应该执行的操作,但唯一渲染的项目是我刚刚尝试删除的项目。我缺少什么?


const [todos, setToDo] = useState(initialToDo);

const [input, setInput] = useState('');


const todoList = (todos) => {

    return (

        todos.map((todo) => {

        return (

            <div className='todo-list flex p-2 w-1/2 justify-between'>

                <p className="px-3">{todo.name}</p>

                <button 

                    className='rounded-sm border-2 px-2'

                    onClick={(e)=>{

                        let item = todos.find(el=>el.id == todo.id);

                        console.log(item)

                        let index = todos.indexOf(item);

                        console.log(index)

                        todos = todos.splice(index, 1)

                        // todos == item

                        setToDo(todos)

                    }}    

                >-</button>

            </div>

    )}))

}


偶然的你
浏览 166回答 3
3回答

守着星空守着你

是的,Array.splice返回删除的元素并改变原始数组,这意味着您可以用来index&nbsp;从列表中删除/更新待办事项todos。执行此操作的最简单方法是以下方法。这是工作示例const todoList = () => {&nbsp; const [todos, setToDo] = useState(initialToDo);&nbsp; const [input, setInput] = useState('');&nbsp; const handleDelete = index => {&nbsp; &nbsp; todos.splice(index, 1)&nbsp; &nbsp; setToDo([...todos])&nbsp; }&nbsp; return (&nbsp; &nbsp; todos.map((todo, index) => {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className='todo-list flex p-2 w-1/2 justify-between'>&nbsp; &nbsp; &nbsp; &nbsp; <p className="px-3">{todo.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; <button&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; className='rounded-sm border-2 px-2'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onClick={() => handleDelete(index)}&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; -&nbsp; &nbsp; &nbsp; &nbsp;</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; )}))}

慕慕森

使用filter而不是使用 进行变异splice。试试这个片段。const TodoList = () => {&nbsp; const [todos, setTodos] = React.useState([&nbsp; &nbsp; { name: 'a', id: 1 },&nbsp; &nbsp; { name: 'b', id: 2 },&nbsp; ]);&nbsp; return todos.map((todo) => {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <p>{todo.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={() => setTodos(todos.filter(item => item.id !== todo.id))} > - </button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; });};const domContainer = document.querySelector('#app');ReactDOM.render(<TodoList />, domContainer);<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script><div id="app"> </div>

陪伴而非守候

splice返回已删除的项目。我建议使用filter类似的东西:setToDo(todos.filter(({&nbsp;id&nbsp;})&nbsp;=>&nbsp;id&nbsp;!=&nbsp;todo.id));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript