简体   繁体   中英

How can I alter the state of a JavaScript object from within a method?

My JavaScript object has a state declared like this:

state = {isFiltered: false}

I have a method changeState() that basically does the following:

this.setState({isFiltered: true});

However, this will give me an error that says that "setState" is not a function. How can I alter this flag from within a method?

Edit: I wasn't understanding how to bind properly. I'll accept a solution as soon as SOF lets me

It seems you have no bounding context for this :

A quick fix is to bind this inside the constructor.

this.changeState = this.changeState.bind(this)

If you want to deep dive, you can follow my another post .

Did you bind your changeState function with this ?

constructor(props) {
    super(props);
    this.state = {isFiltered: true};

    // This binding is necessary to make `this` work in the callback
    this.changeState = this.changeState.bind(this);
    ...

The error is due to different context.

Context is concept which relates 'this' to be associated with specific scope.

For solving the above issue you need to bind your changeState() function using bind().

This will allow changeState to use the context of class where you can access the setState method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM