2017-10-18 219 views
0

有關於響應路由器的問題。React路由器顯示所有路由的一個組件(頭)

我有一個標題項目,我想顯示所有路線。當然,我希望這成爲用戶的一部分,以便用戶可以點擊導航中的項目。

目前我有我的<Header />以外我的<Router>,我猜這是行不通的,因爲我的路由器然後不知道重新渲染?

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' 
    <div> 
    <Header /> 
    <Router> 
     <Switch> 
     <Route exact path="/" component={Posts} /> 
     <Route exact path="/:category/:postId" component={PostDetails} /> 
     <Route path="/:category" component={CategoryView} /> 
     </Switch> 
    </Router> 
    </div> 

而且我的頭例如具有<Link to="/">LOGO</Link>

+0

你採用div嘗試

以上
? – dpetrini

+0

當您點擊導航鏈接時,您的路線組件是不是重新呈現的問題嗎?即從*/category1 *移動到*/category2 * –

+0

@dpetrini我還沒有嘗試過。 –

回答

0

下實現概述了這種解決方案的最佳實踐。

或者,您可以嘗試簡單地將您的<Header/>組件嵌套到您的<Router/>組件中。

此外,您的<Switch/>組件是不必要的。

import { 
    BrowserRouter as Router, 
    Route 
} from 'react-router-dom' 

ReactDOM.render(
    <Router> 
    <Application> 
     <Route exact path="/" component={Posts} /> 
     <Route exact path="/:category/:postId" component={PostDetails} /> 
     <Route path="/:category" component={CategoryView} /> 
    </Application> 
    </Router> 
, document.querySelector('#ROOT')) 

const Application = (props) => (
    <div> 
    <Header/> 
    {props.children} 
    </div> 
) 
0

我在回答評論:

class App extends Component { 
    render() { 
    return (
     <BrowserRouter> 
     <div> 
      <Header /> 
      <Switch> 
      <Route exact path="/" component={Posts} /> 
      <Route exact path="/:category/:postId" component={PostDetails} /> 
      <Route path="/:category" component={CategoryView}/
      </Switch> 
      <Footer /> 
     </div> 
     </BrowserRouter> 
    ); 
    } 
} 
1

當您更改位置,但同樣的路線是匹配,你的分量不重新安裝,只接收新的道具。

因此,您可以使用componentWillReceiveProps鉤使用新的路線PARAMS(如nextProps.match.params.category)更新組件:

... 

componentWillReceiveProps(nextProps) { 

    // Update component using nextProps 

} 

...