【问题标题】:accessing state data in componentDidMount访问 componentDidMount 中的状态数据
【发布时间】:2016-08-25 21:21:27
【问题描述】:

为什么无法在 componentDidMount 中访问 this.state.board?据我了解,一旦组件被渲染,componentDidMount 就会立即被触发,并且只触发一次。

我正在尝试设置 Google Analytics 电子商务跟踪器,因此我认为设置它的最佳位置是在 componentDidMount 中,因为它确保 GA 跟踪器只被调用一次。但是,我无法访问任何状态数据以发送回 GA。有什么想法吗?

    //function which establishes state
    function getEditorState() {
        var board = Editor.getCsb();
        var similarBoard = Editor.getSimilarLsbs();
        return {
            board: board,
            similarBoard: similarBoard,
            editing: Editor.isEditing(),
            hoverColor: Editor.getHoverColor(),
            variant: Editor.variant(),
            lidAndLsb: Editor.getLidAndLsb()
        };
    }



  //component    
    var CsbEditorApp = React.createClass({

            getInitialState: function () {
                return getEditorState();
            },

            componentDidMount: function () {
              console.log(this.state.board); // <---- this returns an empty object.
              Editor.addChangeListener(this._onChange);
              SbAction.loadCsb(this.props.params.cid);
           }, 

           render: function() {
             console.log(this.state.board); // <---- this returns the the board object with data. 
           return (
            <div className={cm('lightbox sb-bg overlay-border')} ref="app">
                <Header board={this.state.board} label={this.state.label} socialLinkStatus={this.state.socialLinkStatus} buyingAll={this.state.buyingAll} />
                <div className="viewer-content">
                    <div id="csb-content">
                        <MetaText className="meta-author" metaKey="author" board={this.state.board} />
                        <BoardMeta board={this.state.board}/>
                        <CsbPanel board={this.state.board hoverColor={this.state.hoverColor} showPanel={showPanel} />

                        <RouteHandler/>
                    </div>
                </div>
            </div>
        );
    }, 
 _onChange: function () {
        this.setState(getEditorState());
        $("#cc_hover").hide();
    }
}); 

【问题讨论】:

  • 你能提供一些代码吗?
  • @LuisPinto 我添加了我的代码
  • 您可以尝试将您的 getEditorState() 放入组件中吗?
  • @LuisPinto 如果我将 getEditorState() 设为 CsbEditorApp 类上的方法,结果是相同的。 componentDidMount 中板子的状态不包含任何数据。
  • 可能是因为您尝试在创建状态之前对其进行控制台记录。您可以尝试在函数中放入一个空对象而不调用 Editor.getCsb() 等...

标签: reactjs google-analytics


【解决方案1】:

console.log 不是一种可靠的调试方法 - 该方法是异步的,实际上可以在您设置侦听器之后甚至在它注册的回调(影响状态)被触发之后调用,所以使用调试器。另外,请尝试注释掉 Editor.addChangeListener(this._onChange); 行,看看它是否会导致问题。

【讨论】:

    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 2019-08-20
    • 2020-08-16
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多