import React from 'react';
class TodoList extends React.Component {
constructor(props){
super(props);
this.state = {
list: [],
inputValue: ''
}
this.handleBtnClick = this.handleBtnClick.bind(this);
this.handleInput = this.handleInput.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
}
handleInput(e){
this.setState({
inputValue: e.target.value
})
}
handleBtnClick(){
this.setState({
list: [...this.state.list, this.state.inputValue],
inputValue: ''
})
}
handleItemClick(index){
const list = [...this.state.list];
list.splice(index, 1);
this.setState({list});
}
render() {
return (
<div>
<div>
<input value={this.state.inputValue} onChange={this.handleInput}/>
<button onClick={this.handleBtnClick}>add</button>
</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index} onClick={this.handleItemClick(index)}>{item}</li>
)
})
}
</ul>
</div>
);
}
}
export default TodoList;
报错信息:Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
onClick={this.handleItemClick(index)} 改成 onClick={() => this.handleItemClick(index)}