React router v4忽略精确

时间:2018-01-10 09:26:22

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

当路径不正确时,我尝试使用React路由器v4渲染NotFound组件或重定向到根路由,但是当我在" /"我的应用程序呈现2个组件。

<Switch>
     <Navbar>
         <Route exact path="/" component={App} />
         <Route path="/Other" component={Other} />
         <Route component={NotFound} />
     </Navbar>
</Switch>

我的Navbar看起来像:

render()
{
    return(
        <div>
            {/*Any content here*/}
            {this.props.children}
        </div>
    );
}

如果我将<Route component={NotFound} />替换为<Redirect to="/" />,它看起来有效,但我收到错误:Warning: You tried to redirect to the same route you're currently on: "/"

感谢您的帮助! :)

1 个答案:

答案 0 :(得分:1)

您的Switch组件的展示位置不正确,它应该将组件子项包装在Routes定义的位置

<Navbar>
     <Switch>
         <Route exact path="/" component={App} />
         <Route path="/Other" component={Other} />
         <Route component={NotFound} />
     </Switch>
</Navbar>