【问题标题】:seState not working设置状态不起作用
【发布时间】:2018-12-09 10:50:01
【问题描述】:

在下面的应用程序组件中,我想根据我定义的函数隐藏一个 div,但它会带来一个错误提示

TypeError: 无法读取未定义的属性“setState”

请问哪里出了问题

class Apps extends Component {
    constructor(props) {
        super(props);
        // Don't do this!
        this.state = { showing: true };
    }

    render() {
        return (
            <div>
             <div className="container">
                <div style={{ display: (this.state.showing ? 'block' : 'none') }}>
                     A Single Page web application made with react
                 </div>
             </div>
                <div className="buttons">
                    <a href='' onClick={this.onclick} >Login</a>
                    <br/>
                    <a href='' >Signup</a>
                    <br />
                    <a href='' >Members</a>
                </div>
            </div>
        );
    }

    onclick(e){
        e.preventDefault();
        this.setState({showing: false});
    }
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6 components


    【解决方案1】:

    你可以使用 bind 或者你可以只使用箭头 ES6 函数而不是绑定它

     onclick = (e) => {
        e.preventDefault();
        this.setState({ showing: false });
      }
    

    【讨论】:

      【解决方案2】:

      你可以例如bind 在 render 方法中将函数传递给 this,这样 this 将是您在 onclick 方法中所期望的。您可以阅读更多关于为什么会这样的信息in the documentation

      <a href='' onClick={this.onclick.bind(this)}>Login</a>
      

      【讨论】:

      • 如果我不绑定它,这会发生什么
      • @AdokiyeIruene 如果不绑定,this 的值将是浏览器中的全局对象window,所以它不会按你的意愿工作。
      【解决方案3】:

      @Tholle 是对的。您必须使用 this 将 onclick 函数绑定到当前类实例。这里默认this指向全局窗口obj,没有setState函数。

      1. 要么将你的函数绑定到 this,然后按照 tholle 的建议调用它。

      2. 你也可以在调用 super(props) 后在构造函数中绑定 this:

        this.onclick = this.onclick.bind(this);

      3. this 也可以使用如下箭头函数隐式绑定:

        this.onclick(e)} ... ./>

      最佳做法是使用第二个选项。因为使用第一个和第三个选项将在每次组件呈现时为函数创建新的引用。但是,如果您对内存消耗或创建小型应用程序没有任何问题,则可以使用第 1 或第 3 选项。

      【讨论】:

        【解决方案4】:

        你可以使用 ES6 箭头函数来绑定词法 this:

        href='' onClick= {(e) => this.onclick(e)}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-29
          • 1970-01-01
          • 2019-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-28
          • 2020-07-07
          相关资源
          最近更新 更多