score:1

Accepted answer

i am not sure why you cannot use arrow functions. they have been supported in all browsers for years - and tools like babel (which you can easily configure bundlers like webpack to use) can convert your code to es5 automatically if you really have to support something like ie.

however, if you really can't, you can just use the old "lexical this" trick that arrow functions were designed as a substitute for:

    const self = this;
    const todoarr = this.state.todos.map(
        function(i){
            return <todolist key = {i.id} arr = {i} handlechange = {self.handlechange}/>
        }
    );

note that this.handlechange = this.handlechange.bind(this) in the constructor doesn't directly help here. (although you do still need it with the above code to make it work.) it's usually used so you can pass this.handlechange as an event handler and have it use the correct this - here, the function inside map already uses its own this so putting this.handlechange in the event handler won't refer to the correct thing, even if you bind.

score:1

array.prototype.map() takes a second argument to set what this refers to in the mapping function, so pass this as the second argument to preserve the current context. [*]

you can try this:

const todoarr = this.state.todos.map(
    function(i){
       return <todolist key = {i.id} arr = {i} handlechange = {this.handlechange}/>
    }, this
);

[*] https://stackoverflow.com/a/30148997/1927991


Related Query

More Query from same tag