Morgan Allen Morgan Allen - 16 days ago 10
React JSX Question

How do I update State outside of Render?

From what I understand, this is what Redux is supposed to solve, but for the time being I'm trying to make this work without it.

When I run this, I realize it is stuck in a pattern. When I run

render
it triggers
updateState()
which changes the state, that triggers a re-render, which triggers
updateState()
and so on...

I am getting the error:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.


What does
componentWillMount
do? What would be the best way to structure this so when I call
<CreateRows />
it will update state, but avoid the loop?

var CreateRows = React.createClass({
updateState : function(){
this.setState({
'people' : [{'name':'something_else', 'email':'test2@gmail.com'}]
});
return (
<tr>
<td>Morgan</td>
<td>test@gmail.com</td>
</tr>

)
}

render: function(){
return (
<tbody>
{this.updateState()}
</tbody>
)
}
});

Answer

It's not recommended to update state on render, but after component has been rendered you can update it for example using componentDidMount method:

var CreateRows = React.createClass({
    updateState : function(){
        this.setState({
            'people' : [{'name':'something_else', 'email':'test2@gmail.com'}]
        });
    },
    componentDidMount: function() {
        this.updateState();
    },
    render: function() {
        return (
            <tbody>
                <tr>
                    <td>Morgan</td>
                    <td>test@gmail.com</td>
                </tr>
            </tbody>
        );
    }
});
Comments