2017-04-21 46 views
1

我希望在反應路由器v4中使用NavLink組件非常簡單,但也許我的組件按照它們應該的方式進行連接。不管怎麼說,我有我在它自己的組件的NavBar,並沒有真的發生在點擊的NavBar ...無法獲得活動鏈接與React Router v4一起使用

<nav style={styles.sidebar}> 
    <div style={styles.logoWrapper}> 
    <span>Logo</span> 
    </div> 
    <ul style={styles.ulList}> 
    <NavLink style={styles.sidebarItem} activeStyle={{backgroundColor: 'white', color: '#313c59'}} to="/app/editor/basicInfo"> 
     <FontAwesome 
     size='3x' 
     border={false} 
     name="wrench" 
     style={{marginBottom: 10}} 
     /> 
     Editor 
    </NavLink> 
    <NavLink style={styles.sidebarItem} activeStyle={{backgroundColor: 'white', color: '#313c59'}} to="/app/utilities"> 
     <FontAwesome 
     size='3x' 
     border={false} 
     name="anchor" 
     style={{marginBottom: 10}} 
     /> 
     Utilities 
    </NavLink> 
    <NavLink style={styles.sidebarItem} activeStyle={{backgroundColor: 'white', color: '#313c59'}} to="/app/settings"> 
     <FontAwesome 
     size='3x' 
     border={false} 
     name="cog" 
     style={{marginBottom: 10}} 
     /> 
     Settings 
    </NavLink> 
    </ul> 
</nav> 

但我不知道這是哪裏的怪事進來,並有興趣,如果任何人都有更好的設計模式...但是我的許多應用程序可能會或可能沒有導航欄,或者它可能完全不同,所以我創建了一個組件來計算出現在要顯示哪個欄。

//inside componentDidUpdate() 
const path = window.location.pathname.split('/')[1]; 

if (path === "app") { 
    this.setState({onLandingPage: false}) 
} 

if (path != "app") { 
    this.setState({onLandingPage: true}) 
} 

//inside render func 
<div> 
    { (this.state.onLandingPage) ? <NavBar /> : <EditorNavBar /> } 
</div> 

這很簡單,它只是檢查第一個路徑名,然後像這樣渲染。這部分工作,但它混淆了道具以某種方式下來。任何智慧或想法都會很棒!

UPDATE:

而且,這裏是我如何結束了在底部的組件...這是用鐳拳頭時間,所以有很多包裝的事情:

const connector = connect(mapStateToProps, mapDispatchToProps); 

export default withRouter(connector(Radium(EditorNavBar))); 
+0

你得到控制檯的任何錯誤? –

+0

@Rendien不,我不知道。我起初是在不使用價值prop和defaultValue prop的情況下在文本區域中顯示值的,我希望這會對問題有所幫助。它沒有:/ –

+0

@ReiDien我會說,我一直試圖註銷導航組件中發生的任何事情,並且我無法得到任何東西。我只是不知道爲什麼。 –

回答

1

NavBar由於Update Blocking未更新。嘗試使用withRouter包裝NavBar。這將在位置更改時重新渲染組件。

P.S.要選擇正確的NavBar一個清潔的方法是用路由(這否定了需要withRouter作爲組件將在通路改變重新渲染像任何其他途徑):

<Switch> 
    <Route exact path="/app" component={EditorNavBar}/> 
    <Route component={NavBar}/> 
</Switch> 
+0

啊,非常感謝那些信息。我很喜歡90%,我確實用Navouter包裹了路由器,但明天我會仔細檢查。但是你說得對,這是更清潔。我也會努力實現這一點。如果我忘記用Router包裝它,會讓你知道。 –

+0

@TaylorKing還有,如果你確實選擇使用路由來渲染你的導航欄,這將不需要使用路由器,因爲它自然會在路徑改變時重新渲染。 –

+0

我確實確認它是用withConnector包裝的,但我也是第一次使用Radium,所以包裝組件一直有點棘手......我會更新我的帖子,以便您可以看到如果感興趣。但更清潔的方法還有一個問題。我傾向於過時,但在「/」我希望家庭組件也加載...我也可以做component = {Home},並添加在路由配置sideBarComponent = {NavBar}?對此有何想法? –