score:3

Accepted answer

use one of these:

  1. this.finalize = this.finalize.bind(this); in constructor
  2. onchange={this.finalize.bind(this)}
  3. onchange={e => this.finalize(e)}
  4. finalize = () => {};

you can read more about the pros and cons here.

score:1

it looks like you've identified the issue. when the finalize() method is called, this is bound to the window.

you can solve the issue by binding the function in the constructor. for example:

    constructor(props) {
            super(props);
            this.state = {
                optionlist: []
            };
            this.finalize = this.finalize.bind(this);
        }

it's generally better to bind in the constructor than to bind in the render method, because if you call bind in the render method, you are generating a new function each time.

for more information, take a look at this: https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56


Related Query

More Query from same tag