我在React中练习待办事项清单,遇到了一个我不理解的问题。无法从处于我状态的数组中删除该项目。我将索引传递给删除函数,然后尝试过滤数组以设置新的状态。
这是我的App组件的代码:
class App extends React.Component {
state = {
tasks : []
}
addToScreen = (task) => {
const tasks = { ...this.state.tasks }
tasks[`task${Date.now()}`] = task
this.setState(prevState => ({
tasks: [...prevState.tasks, task]
}))
}
deleteTask = index => {
const reducedArr = this.state.tasks.filter( (item) => {
return item[index] !== item
})
this.setState({
tasks: reducedArr
})
}
render() {
return (
<>
<Input addToScreen={this.addToScreen}/>
<Screen tasks={this.state.tasks} deleteTask={this.deleteTask}/>
</>
);
}
}
这是我的屏幕组件:
class Screen extends React.Component {
render() {
return (
<ul>
{this.props.tasks.map((key, index) => <li key={index}>{key}
<button onClick={() => this.props.deleteTask(index)}>x</button>
</li>)}
</ul>
)
}
}
因此,当您按我的屏幕组件上的按钮时,应该从状态中删除特定值。感谢您的帮助或任何提示!
答案 0 :(得分:1)
它应该是item[Index]
回调函数中项目的索引,而不是filter
。
赞:
deleteTask = index => {
const reducedArr = this.state.tasks.filter((item, itemIndex) => {
return itemIndex !== index
})
this.setState({
tasks: reducedArr
})
}
还要将updater function与setState一起使用(因为您正在更新数组并且setState本质上是异步的,请查看react文档以获取更多详细信息),编写与以下命令相同的函数:
deleteTask = index => {
this.setState(prevState => ({
tasks: prevState.tasks.filter((item, itemIndex) => itemIndex != index)
}))
}
答案 1 :(得分:1)
我也是React的新手!我刚刚在做类似的事情:
deleteTask = (index) => {
const reducedArr = [...this.state.tasks];
reducedArr.splice(index, 1);
this.setState({tasks: reducedArr})
}
编辑:此处归功于Academind的MaximilianSchwarzmüller。我正在做《反应完全指南》
答案 2 :(得分:0)
正确的方法是使用splice
。它从数组中删除项目,并有选择地用新项目替换它们。这是语法:
array.splice(start[, deleteCount[, item1[, item2[, ...]]]]);
您的函数可能显示为:
deleteTask (index) { // Just so you don't need to bind `this`
this.state.tasks.splice(index, 1);
this.setState({
tasks: this.state.tasks
})
}
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
答案 3 :(得分:0)
您需要将this
绑定到您的处理程序
render() {
return (
<>
<Screen
tasks={this.state.tasks}
deleteTask={this.deleteTask.bind(this)}
/>
</>
);
}
此外,您的过滤器存在错误,它是按值而不是按索引过滤掉的。我修好了:
const reducedArr = this.state.tasks.filter((_, key) => {
return key !== index;
});
答案 4 :(得分:0)
删除任务方法:
deleteTask = indexToRemove => {
this.setState(state => ({
tasks: state.tasks.filter((_, index) => index !== indexToRemove)
}));
}
添加任务方法:
addToScreen = (task) => {
this.setState(state => ({
tasks: state.tasks.concat(task)
}));
}
屏幕组件:
class Screen extends React.Component {
handleRemove => event => {
const target = event.currentTarget || event.target;
const { index } = target.dataset;
this.props.deleteTask(+index);
}
render() {
return (
<ul>
{
this.props.tasks.map((task, index) => (
<li key={index}>
{task}
<button onClick={this.handleRemove} data-index={key}>x</button>
</li>
))
}
</ul>
)
}
}