反应,setState在我的反应应用程序中不起作用

时间:2018-11-04 06:21:34

标签: javascript reactjs setstate

这是我的代码:

import React, { Component } from 'react';

class Counter extends Component {
    constructor(props){
        super(props);
        this.state = {
            number : 0
        };

        this.handleIncrease = this.handleIncrease.bind(this);
        this.handleDecrease = this.handleDecrease.bind(this);
    }

    handleIncrease = () => {
        this.setState=({
            number: this.state.number + 1
        });
        console.log("handleIncrease()");
    }
    handleDecrease = () => {
        this.setState({
            number: this.state.number - 1
        });
        console.log("handleDecrease()");
    }

    render(){
        return (
            <div>
                <hr/>
                <h1>Counter</h1>
                <p>number : {this.state.number}</p>
                <button onClick={this.handleIncrease}>+</button>
                <button onClick={this.handleDecrease}>-</button>
                <hr/>
            </div>
        )
    }
}

export default Counter;

当我按下-按钮时,它可以工作,但是当我按下+按钮并出现错误时,它不起作用:

  

TypeError:_this.setState不是函数   Counter._this.handle减少

2 个答案:

答案 0 :(得分:0)

import React, { Component } from 'react';

class Counter extends Component {
    constructor(props){
        super(props);
        this.state = {
            number : 0
        };

        this.handleIncrease = this.handleIncrease.bind(this);
        this.handleDecrease = this.handleDecrease.bind(this);
    }

    handleIncrease = () => {
       //here remove equal
        this.setState({
            number: this.state.number + 1
        });
        console.log("handleIncrease()");
    }
    handleDecrease = () => {
        this.setState({
            number: this.state.number - 1
        });
        console.log("handleDecrease()");
    }

    render(){
        return (
            <div>
                <hr/>
                <h1>Counter</h1>
                <p>number : {this.state.number}</p>
                <button onClick={this.handleIncrease}>+</button>
                <button onClick={this.handleDecrease}>-</button>
                <hr/>
            </div>
        )
    }
}

export default Counter;

答案 1 :(得分:0)

删除等号:

handleIncrease = () => {
    >>>> this.setState({
       number: this.state.number + 1
     });
     console.log("handleIncrease()");
    }

此外,在使用先前状态设置新状态时,请在setState中传递一个函数,因为状态更新可以是异步的。

更多信息:https://reactjs.org/docs/state-and-lifecycle.html