首页 文章

React router v4忽略精确

提问于
浏览
2

我正在尝试使用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 回答

  • 1

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

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

相关问题