如何使用React删除待办事项列表中的项目
我正在使用React创建一个待办事项应用程序,在我的应用程序中,当我单击x按钮以删除项目并使用console.log检查当前数组时,我可以看到该数组已正确更新为所需的项目删除从数组列表中删除的内容,但Dom仅呈现我要删除的项目,而不是整个数组
I am using React to create a to do list app, in my app when I click x button to remove an Item and using console.log to check current array, I can see the array is updated correctly with the Item I want to remove removed from the list of array, but the Dom only renders the Item I want to remove instead of the whole array
import React from 'react';
import ReactDom from 'react-dom';
class TodoList extends React.Component{
constructor(props){
super(props);
this.state={
todoList:[],
todo:''
}
};
onValueChange=(e)=>{
const todo=e.target.value;
this.setState({todo})
};
removeItem=(props)=>{
this.setState({todoList:this.state.todoList.splice(props,1)})
console.log(this.state.todoList)
};
onSubmit=(e)=>{
e.preventDefault();
const {todoList,todo}=this.state
this.setState({todoList:[...todoList,todo]})
this.setState({todo:''})
console.log(this.state.todoList)
};
render(){
const myList=this.state.todoList.map((todo,index)=>(
<li key={index}>
{todo}
<button onClick={()=>this.removeItem(index)}>x</button>
</li>
))
return (
<div>
<form onSubmit={this.onSubmit}>
<input
type="text"
value={this.state.todo}
onChange={this.onValueChange}
autoFocus
placeholder='todo'
/>
</form>
<ol>
{myList}
</ol>
</div>
)
};
};
ReactDom.render(<TodoList/>,document.getElementById('app'));
这是图片
在图片中,您可以看到控制台显示了删除了项目'5'的阵列,但是屏幕仅显示了项目'5'而不是项目1-4.
in the picture you can see that the console shows the array with item '5' removed, but the screen only show the item '5' instead of the items 1 to 4
修复您的removeItem
removeItem = (props)=> {
this.state.todoList.splice(props, 1)
this.setState({todoList: this.state.todoList})
console.log(this.state.todoList)
};
Array.prototype.splice()
方法修改数组.
Array.prototype.splice()
method modify the array in place.
返回值
包含删除的元素的数组.如果只有一个元素是 移除后,将返回一个元素的数组.如果没有元素 删除后,将返回一个空数组.
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.