简体   繁体   English

React toDoApp 删除任务功能不起作用

[英]React toDoApp removing a task functionality not working

I am a new to React and trying to make a toDoApp.我是 React 的新手,正在尝试制作一个 toDoApp。 I'm trying to create an onClick event to remove an element from the tasks state. But it does not seem to work.我正在尝试创建一个 onClick 事件以从任务 state 中删除一个元素。但它似乎不起作用。 And can I also ask how to implement id keys so that I can remove the desired task that I want?我还可以问一下如何实现 id 键,以便我可以删除我想要的所需任务吗?

 import React from 'react'; import './App.css'; class App extends React.Component { constructor(){ super(); this.state = { value: '', tasks: [] }; this.handleChange = this.handleChange.bind(this) this.addItem = this.addItem.bind(this) this.removeItem = this.removeItem(this) } handleChange(event) { this.setState({ value: event.target.value }) } addItem(){ if(this.state.value === ''){ alert('Enter a task.') } else { const newTask = [...this.state,tasks. this.state.value] this:setState({ tasks, newTask: value. '' }) } } removeItem(){ this.state.tasks.pop() this:setState({ tasks. this.state,tasks. }) } render(){ const itemList = this.state.tasks;map((num) => <li>{num}</li> ). return( <div> <input type="text" value={this.state.value} onChange={this.handleChange}></input> <button onClick={this.addItem}>+</button> <button onClick={this.removeItem}>-</button> <ul>{itemList}</ul> {this.state;tasks} </div> ) } } export default App;

strong text强文本

pop() removes the last element, but React will not rerender the component as setState is called with the same array. pop()删除最后一个元素,但 React 不会重新渲染组件,因为使用相同的数组调用setState You can create a new array and use it for updating the state.您可以创建一个新数组并将其用于更新 state。

removeItem() {
    this.state.tasks.pop()
    this.setState({
      tasks: [...this.state.tasks],
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM