M
M
Michael R.2019-05-31 12:01:07
JavaScript
Michael R., 2019-05-31 12:01:07

How to change the state correctly?

Greetings!
I wrote the first component in React, but I ran into a problem: after rendering, on click, the value of state.prop increases without problems, but it is not possible to increase the value of state.prop before rendering.
How to correctly increase the state.prop value before rendering?

class App extends React.Component {

    constructor() {
        super();
        this.state = {prop: 1}
    }

    state_change() {
        this.setState({prop: ++this.state.prop});
    }

    render() {

        this.state_change.bind(this); // prop не был увеличен

        return <div>
            <p>{this.state.prop}</p>
            <input type="button" value="Обновить" onClick={this.state_change.bind(this)}/>
        </div>;
    }

}

ReactDOM.render(<App/>, document.getElementById('body'));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2019-05-31
@Mike_Ro

incProp = () => {
  this.setState(state => ({
    prop: state.prop + 1,
  }));
};

render() {
  return <button onClick={this.incProp}>...</button>;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question