admin管理员组

文章数量:1279008

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 ponent 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 : ""
        }
    },
    ponentDidMount() {
        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 ponentDidMount but it is hitting only once. Whats wrong with my code can anyone help me?

Thanks

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 ponent 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 : ""
        }
    },
    ponentDidMount() {
        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 ponentDidMount but it is hitting only once. Whats wrong with my code can anyone help me?

Thanks

Share Improve this question asked Mar 29, 2017 at 13:36 GowthamGowtham 3954 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

He is talking about ponentDidUpdate, not ponentDidMount.


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

本文标签: javascriptReactsetState in componentDidMount not causing infinite loopStack Overflow