react 报错this.setState

ES6中 this 只能在构造函数中使用了,因此this.setState()这个函数也就不能直接调用了。

import React, { Component } from 'react';

class Home extends Component {
    constructor(){
        super();
        //需要在构造函数中用bind方法传入this
        this.addNum = this.addNum.bind(this);
        this.state = {
            num:0
        }
    }

    componentDidMount(){
        console.log(this.props.data)
    }
    addNum(){
        this.setState({
            num:this.state.num+1
        })
    }
    render() {
        return (
        <div>
            <button onClick={this.addNum}>click me</button>
            <span>Click Count:{this.state.num}</span>
        </div>
        );
    }
}

export default Home;

猜你喜欢

转载自blog.csdn.net/Lei_zhen96/article/details/84855114