I'm developing a simple 'to do list' react app (new to React.js). I have adding items to a list working but deleting items raises a question. Within my parent react component, i have the following code:
import ToDoEntries from './to_do_entries.jsx';
class ToDoList extends React.Component {
constructor(props) {
super(props);
this.state = { list: [] }
this.add = this.addItem.bind(this);
this.removeItem = this.removeItem.bind(this);
}
addItem(e) { //removed to avoid tl:dr }
render() {
return(
<form onSubmit={this.add}>
<input placeholder='Enter item' type='text' ref={(el) => {this._input = el;} }/>
<button>Add</button>
</form>
<ToDoEntries entries={this.state.list}
removeCallback={this.removeItem}
/>
);
}
}
My to_do_entries.jsx
component:
class ToDoEntries extends React.Component {
constructor(props) {
super(props);
}
renderItems() {
const { entries, removeCallback } = this.props;
function createTasks(item) {
return <li key={item.key}>{item.text}</li>
}
var listItems = entries.map(function(item) {
return(<li onClick={removeCallback} key={item.key}>{item.text}</li>)
})
return listItems;
}
render() {
var todoEntries = this.renderItems();
return(
<ul>
{todoEntries}
</ul>
);
}
}
export default ToDoEntries;
Running this code bring:
Warning: setState(…): Cannot update during an existing state transition
Question:
why does to_do_entries.jsx
's render immediately execute the callback when an item gets added i.e:
var listItems = entries.map(function(item) {
return(<li onClick={removeCallback(id)} key={item.key}>{item.text}</li>)
})
However, adding .bind(null, id)
to removeCallback ie. <li onClick={removeCallback.bind(null, id)} />
does not?
onClick={removeCallback(id)}
is firing/calling removeCallback immediately and whyonClick={removeCallback.bind(null, id)}
does not fire/call removeCallback immediately? – Johnthis
context and function callbacks i.efunctionName()
vsfunction
has been mind-boggling me for some time now. @John – soups