Y
Y
yankoyski2018-12-03 13:48:51
React
yankoyski, 2018-12-03 13:48:51

Why is the old value of state displayed?

Why console.logdoes it display the old value from state if setState worked before?

import React, {Component} from "react";

export default class Test extends Component{

    constructor(props) {

        super(props);

        this.state = {
            test: false
        }
    }

    componentWillMount() {

        this.setState({
            test: !this.state.test
        });

        console.log(this.state.test)//false
    }


    render() {

        return (
            <div />
        )
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2018-12-03
@yankoyski

Because this.propsand this.statemay be updated asynchronously, you should not rely on their values ​​for calculating the next state.

Documentation
This is correct:
this.setState(
  (state) => ({test: !state.test}),
  () => console.log(this.state.test)
);

A
Anton Spirin, 2018-12-03
@rockon404

this.setState(
  prevState => ({ test: !prevState.test }),
  () => console.log(this.state.test),
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question