【问题标题】:How can I alter the state of a JavaScript object from within a method?如何从方法中更改 JavaScript 对象的状态?
【发布时间】:2019-08-07 19:53:43
【问题描述】:

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

state = {isFiltered: false}

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

this.setState({isFiltered: true});

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

编辑:我不明白如何正确绑定。只要 SOF 允许,我就会接受解决方案

【问题讨论】:

  • 你能添加完整的代码sn-p吗?在此之前我有一个问题,为什么当 react 给你 setState 时你想要一个单独的方法来 changeState?

标签: javascript reactjs


【解决方案1】:

您似乎没有this 的边界上下文:

快速解决方法是在构造函数中绑定this

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

如果你想深入了解,可以关注我的another post

【讨论】:

    【解决方案2】:

    您是否将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】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        相关资源
        最近更新 更多