简体   繁体   中英

React : setState in componentDidMount not causing infinite loop

I am new to ReactJS. When i am reading ReactJS Blueprint book author had specified that

"but take care to never run setState in here, as that will trigger an endless update loop."

So, i have created a below simple component but i did not see any such infinite loop happening.

'use strict';
import React from 'react';
import { render } from 'react-dom';
const App = React.createClass({
    displayName : "SG",
    getDefaultProps() {
        return {
            age : "24"
        }
    },
    getInitialState() {
        return {
            date : ""
        }
    },
    componentDidMount() {
        debugger;
        var d = new Date();
        this.setState({date: d.getMilliseconds().toString()});
    },
    render() {
        return (
            <section>
                <h1>Demo App</h1>
                <p>Name : {this.props.name}</p>
                <p>Age : {this.props.age}</p>
                <p>date : {this.state.date}</p>
            </section>
        );
    }
});
render (<App name='Gowtham S'/>, document.getElementById('container'));

I kept debugger in componentDidMount but it is hitting only once. Whats wrong with my code can anyone help me?

Thanks

He is talking about componentDidUpdate , not componentDidMount .


When you setState in componentDidUpdate , the latter is being called again because the component should update, which results in endless recursion. On the other hand, componentDidMount is only called on the initial render.

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