为什么我在这里得到一个错误?React Todo列表



我试图使用React创建一个待办事项列表,但我似乎无法理解为什么我得到错误:"警告:无法在现有状态转换期间更新(如render)。渲染方法应该是props和state的纯函数。">

代码如下:

import React from 'react'
import ReactDOM from 'react-dom'
class Todo extends React.Component{
constructor(props){
super(props)
this.state = {
input: '',
list: []
}
this.handleChange = this.handleChange.bind(this)
this.reset = this.reset.bind(this)
this.removeItem = this.removeItem.bind(this)
this.add = this.add.bind(this)
}
add(){ //Adds a new task

const newItem = {
value: this.state.input,
id: Math.random + Math.random
};
const listed = [...this.state.list]
listed.push(newItem)
this.setState({
input: '',
list: listed
})
}
removeItem(id){ //deletes a task
const list = [...this.state.list]
const updatedList = list.filter(obj => {
return obj.id !== id
})
this.setState({
list: updatedList
})
}
handleChange(e){
this.setState({input: e.target.value})
}
reset(e){
e.preventDefault()
}
render(){
return (
<div>
<form action="" onSubmit={this.reset}>
<input type="text" value={this.state.input} placeholder='Enter a task..' onChange={this.handleChange}  />
<button onClick={this.add}>Add Task</button>
{this.state.list.map(item => {   //updates when a task is added or removed
return (
<div key={item.id}>
<h1>{item.value}</h1>
<button onClick={this.removeItem(item.id)}>X</button>
</div>
)
})}
</form>
</div>
)
}
}
ReactDOM.render(<Todo />,document.getElementById('root'))

因为你在渲染时调用removeItem。它需要包装在一个单独的函数中:

<button onClick={() => this.removeItem(item.id)}>X</button>

所以你只叫它onClick而不叫它on render

  1. <button onClick={this.removeItem(item.id)}>X</button>在此按钮中,由于最后出现了(),您提供的事件处理程序将立即运行。为了防止这种情况,并且仍然提供您的参数item.id,您可以将处理程序this.removeItem(item.id)包含在另一个函数中。我喜欢这个箭头函数所以我的是这样的<button onClick={ ()=>this.removeItem(item.id) }>X</button>.

  2. Math.random + Math.random没有返回您想要的元素键的数字。这是因为你在告诉JS运行函数并返回int值时忽略了包含()

在做了这些更改之后,我在codependency中运行它。IO和它似乎工作良好。

相关内容

最新更新