如何在Render之外更新State?

时间:2016-11-16 13:08:59

标签: reactjs

根据我的理解,这是Redux应该解决的问题,但目前我正试图在没有它的情况下完成这项工作。

当我运行它时,我意识到它被困在一个模式中。当我运行render时,它会触发updateState()更改状态,触发重新渲染,触发updateState()等等......

我收到错误:

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.

componentWillMount做什么?什么是最好的结构方式,所以当我调用<CreateRows />它会更新状态,但避免循环?

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>
        )
    }
});

1 个答案:

答案 0 :(得分:0)

不建议更新render上的状态,但在呈现组件后,您可以使用 componentDidMount 方法更新它:

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>
        );
    }
});