我正在開發一個react/redux應用程序,並希望我的選項卡式組件使用redux存儲區作爲其活動選項卡狀態。我試圖以儘可能通用的方式實現這一點,以在我所有不同的選項卡組件之間共享功能;這導致了一個通用的標籤面板具有以下渲染方法:爲什麼在render()中使用react/redux克隆具有新道具的元素時會發出警告?
render() {
var activeTarget = this.props.panelState.tabPanes[this.props.tabPanelID] ? this.props.panelState.tabPanes[this.props.tabPanelID].activeTarget : this.props.defaultTarget;
var tabs = this.props.panelState.tabs;
var tabPanelID = this.props.tabPanelID;
// Add the tabPanelID and active properties to the tab pane children
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
tabPanelID: tabPanelID,
active: activeTarget === child.props.id
})
);
// Render complete tab pane
return (
<div>
<ul className="nav nav-tabs">
{this.buildTabs()}
</ul>
<div className="tab-content">
{childrenWithProps}
</div>
</div>
);
}
然而,地圖調用似乎導致以下警告:
警告:的setState(...):不能更新在現有狀態轉換期間(例如
render
或另一個組件的構造函數)。渲染方法應該是道具和狀態的純粹功能;構造函數的副作用是一個反模式,但除非我記錯了,我沒有真正改變此狀態可以被移至`componentWillMount
,所以我不能肯定爲什麼我得到這個警告。儘管如此,我還是比較陌生的,所以我很可能錯過了一些東西或誤解。
任何援助將不勝感激。
編輯:對於那些想知道,這裏是buildTabs(的)內容:
buildTabs() {
var result = [];
var tabPanelID = this.props.tabPanelID;
// Create a tab for each tab in the props
for(var i = 0; i < this.props.tabs.length; i++) {
result.push
(
<Tab tabPanelID={this.props.tabPanelID} bare={this.props.tabs[i].bare} key={i} target={this.props.tabs[i].target}
active={this.props.panelState.tabPanes[tabPanelID] ?
(this.props.panelState.tabPanes[tabPanelID].activeTarget === this.props.tabs[i].target) :
this.props.tabs[i].target == this.props.defaultTarget}
additionalClasses={this.props.additionalTabClasses}>
{this.props.tabs[i].contents}
</Tab>
)
}
return result;
}
我根本不包括在此之前,因爲我可以離開,在沒有問題的,但去除呼籲兒童。地圖消除了警告。
你是否正在'buildTabs'方法中調用setState()? – Pcriulan
是的,我要說,'this.buildTabs()'中發生了什麼? – John
我已經添加了該代碼供您查看。正如編輯中提到的那樣,之前我沒有包括它,因爲它可以保留而不會導致警告。 –