【发布时间】: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() 等...