具有相似路径的React Router v4组件(固定和动态路径参数)是"重叠"

时间:2017-12-22 18:45:45

标签: reactjs react-router react-router-v4

我的路线设置如下:

<Route path="/chat/:id" component={Chat} />
<Route path="/chat/new" component={NewChat} />

当我转到chat/new时,它还显示{Chat}。当我转到NewChat时,有没有办法专门致电/chat/new

2 个答案:

答案 0 :(得分:8)

您将使用Switch并重新排序您的路线,因为Switch会渲染第一个匹配的Route

<Switch>
   <Route path="/chat/new" component={NewChat} />
   <Route path="/chat/:id" component={Chat} />
</Switch>

答案 1 :(得分:0)

<Route 
    path="/chat/:id/" 
    render={ props => { 

        if( props.location.pathname != '/chat/new') return <Chat {...props} /> 
        else return null;

    } } 
/>
<Route path="/chat/new" component={NewChat} />

取决于您的设置,这也可以是解决方案