React - 刷新保存计数器

时间:2018-03-07 13:33:43

标签: reactjs redux refresh counter

我有一个组件,它运作良好

好的,在构造函数中我有:

  constructor(props) {
    super(props);
    this.state = {
        count: 0
    }

我也有功能:

onClick(e) {
    this.setState({
        count: this.state.count + 1
    });
}

如何不是每次 0 ,而是在刷新后进行更新?

1 个答案:

答案 0 :(得分:1)

这是一个增加计数器和重置计数器的简单示例。 如果您希望此值在页面重新加载后仍然存在,则无法将值保持在该状态。不确定您是否只在寻找

class TestJs extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        }
        this.onClick = this.onClick.bind(this);
        this.resetCounter = this.resetCounter.bind(this);
    }

    onClick(e) {
        this.setState({
            count: this.state.count + 1
        });
    }

    resetCounter(){
        this.setState({count : 0});
    }

    render() {
        return (
            <div>
                Counter value is {this.state.count}
                <br/>
                <button onClick={this.onClick}> Increase counter</button>
                <br/>
                <button onClick={this.resetCounter}> Reset counter</button>
            </div>
        );
    }
}

export default TestJs
相关问题