[英]Push state updates directly to conditionally rendered React component?
我正在構建一個React應用程序,並具有一個選項卡部分,在其中單擊選項卡將呈現特定組件。
首先,我的父組件:
class Interface extends Component { constructor(props) { super(props); this.chooseTab = this.chooseTab.bind(this); this.state = { current: 'inventory', inventory: [], skills: [], friends: [], notifications: {} }; } chooseTab(tabID) { this.setState({ current: tabID }); chooseComponent(tabID) { if (tabID === 'skills') return Skills; else if (tabID === 'inventory') return Inventory; else if (tabID === 'friends') return FriendsList; } render() { const tabID = this.state.current; const CustomComponent = this.chooseComponent(tabID); return ( <div className='column' id='interface'> <div className='row' id='tabs'> <ActiveTab current={this.state.current} tabID='skills' chooseTab={this.chooseTab} /> <ActiveTab current={this.state.current} tabID='inventory' chooseTab={this.chooseTab} /> <ActiveTab current={this.state.current} tabID='friends' chooseTab={this.chooseTab} /> </div> <TabBody> <CustomComponent data={this.state[tabID]} notifications={this.state.notifications} /> </TabBody> </div> ); } }
呈現三個ActiveTab和一個TabBody:
const ActiveTab = (props) => { const isActive = props.tabID === props.current ? 'active' : 'inactive'; return ( <button className={`active-tab ${isActive}`} onClick={() => props.chooseTab(props.tabID)} >{props.tabID} </button> ); }; const TabBody = (props) => { return ( <div className='tab-body'> {props.children} </div> ); };
這很好,並且顯然是處理此問題的一種預期方式 。 但是,我希望能夠將notifications
狀態對象移動到我的FriendsList
組件中(因為它對朋友是唯一的),並且即使另一個FriendsList
不是FriendsList
當前呈現的組件,也可以從另一個組件中觸發setState
。 ,未安裝)。
我當前正在使用全局可用的actions
關閉觸發遠程狀態更改,其中在目標元素的ComponentWillMount()
生命周期方法中定義了特定的動作和setState
,並且它是通過激活遠程狀態更改的任何組件執行的。 為了簡潔起見,我將其排除在Interface
。
您將如何處理? 我唯一的選擇是將notifications
留在Interface
,在其中定義動作,然后讓React處理傳遞的props嗎? 還是有一種構建我的選項卡組件和條件渲染的方法,這樣我就可以觸發狀態更改,從一個單獨的組件到一個選項卡中未顯示的組件, FriendsList
notifications
及其相應的動作移到FriendsList
?
我遇到了與您幾周前類似的問題,如果您還沒有決定采用Redux,MobX甚至Flux之類的州經理,我認為您應該將道具傳遞給他們的孩子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.