Reputation: 151
Simple todo list. I want to add a delete function but getting error:
proxyConsole.js:56 Warning: setState(...): Cannot update during an existing state transition (such as within
render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved tocomponentWillMount
.
I might meesed with the binding as I try to get a grasp of it.
class App extends Component {
constructor(props) {
super(props);
this.onDelete = this.onDelete.bind(this);
this.state = {
todos: ['wash up', 'eat some cheese', 'take a nap'],
};
}
render() {
var todos = this.state.todos;
todos = todos.map(function(item, index){
return(
<TodoItem item={item} key={index} onDelete={this.onDelete}/>
)
}.bind(this));
return (
<div className="App">
<ul>
{todos}
</ul>
</div>
);
}
onDelete(item){
var updatedTodos = this.state.todos.filter(function(val, index){
return item !== val;
});
this.setState({
todos:updatedTodos
});
}
}
class TodoItem extends Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete(this);
}
render(){
return(
<li>
<div className="todo-item">
<span className="item-name">{this.props.item}</span>
<span className="item-delete" onClick={this.handleDelete}> x</span>
</div>
</li>
);
}
handleDelete(){
this.props.onDelete(this.props.item);
}
}
Upvotes: 1
Views: 834
Reputation: 3932
I think you are invoking handleDelete handler in child component's constructor. It should be :
this.handleDelete = this.handleDelete.bind(this);
class App extends React.Component {
constructor(props) {
super(props);
this.onDelete = this.onDelete.bind(this);
this.state = {
todos: ["wash up", "eat some cheese", "take a nap"]
};
}
render() {
var todos = this.state.todos;
todos = todos.map(
function(item, index) {
return <TodoItem item={item} key={index} onDelete={this.onDelete} />;
}.bind(this)
);
return (
<div className="App">
<ul>
{todos}
</ul>
</div>
);
}
onDelete(item) {
var updatedTodos = this.state.todos.filter(function(val, index) {
return item !== val;
});
this.setState({
todos: updatedTodos
});
}
}
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
render() {
return (
<li>
<div className="todo-item">
<span className="item-name">{this.props.item}</span>
<span className="item-delete" onClick={this.handleDelete}> x</span>
</div>
</li>
);
}
handleDelete() {
this.props.onDelete(this.props.item);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>
Upvotes: 2