简体   繁体   中英

Why doesn't the state change?

I can't understand why console.log() works, but state still doesn't change?

Means setState() is called but not rendered new...

I tried async version setState() but it's still not working.

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = {fontSize: `${20}px`};
        setInterval( 
            () => {
                console.log("ok"); // ok, ok, ok ...
                this.setState(
                    {
                        fontSize: ++prevState.fontSize+"px"
                    }
                )
            },
            1000
        );
    }
    render() {
        let s1 = {
            fontSize: this.state.fontSize
        }
        return <p style={s1}>{this.props.text}</p>;
    }
}

ReactDOM.render(
    <Hello text="sadadadsdad" />,
    document.getElementById("root")
)

You need to change a couple of things in your code:

  • You are trying to access prevState inside setState but you are not using the arrow function thus prevState is undefined .

  • You declared fontSize as a string in your initial state data so incrementing won't work since it should be a number.

Lastly, don't forget to clear that interval in componentWillUnmount .

 constructor(props) { super(props); this.state = { fontSize: 20 }; setInterval(() => { this.setState(prevState => ({ fontSize: ++prevState.fontSize })); }, 1000); } 

See working example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM