代码之家  ›  专栏  ›  技术社区  ›  Francisco José Letterio

如何从方法中更改JavaScript对象的状态?

  •  -1
  • Francisco José Letterio  · 技术社区  · 5 年前

    我的JavaScript对象的状态声明如下:

    state = {isFiltered: false}
    

    我有一个方法changeState(),它基本上执行以下操作:

    this.setState({isFiltered: true});
    

    但是,这会给我一个错误,说“setState”不是一个函数。如何在方法中更改此标志?

    编辑:我不知道如何正确绑定。我会尽快接受解决方案

    3 回复  |  直到 5 年前
        1
  •  2
  •   Bhojendra Rauniyar    5 年前

    你似乎没有什么限制 this :

    一个快速的解决办法是捆绑 在构造器内部。

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

    如果你想潜水,你可以跟着我 another post .

        2
  •  1
  •   ttulka    5 年前

    你把你的 changeState 功能 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);
        ...
    
        3
  •  0
  •   Raj Saraogi    5 年前

    错误是由于不同的上下文造成的。

    上下文是将“this”与特定范围相关联的概念。

    要解决上述问题,需要使用bind()绑定changeState()函数。

    这将允许changeState使用可以访问setState方法的类的上下文。