React 路由器不会找不到页面

我有一个标题,我想在某些页面上显示。所以我把我想要的页面包裹在 a 周围<></>并且成功了。但“NotFound”页面现在永远不会显示,并且标题位于空白页面上,而不是“未找到”页面上。我做错了什么以及如何解决它?


        <Switch>

            <Route path='/login' component={Login}></Route>

            <Route path='/signup' component={SignUp}></Route>


            <>

                <Header />

                <Route path='/cool-page' component={Cool}></Route>

                <Route path='/another-page' component={Another}></Route>


                <Route path='/' exact component={() => <Redirect to='/cool-page'></Redirect>}></Route>

            </>


            // This never get called...

            <Route path='/' component={NotFound}></Route>

        </Switch>


白衣染霜花
浏览 161回答 4
4回答

胡说叔叔

我在文档中找不到它,但我的感觉是(我自己测试了它),<></>您的交换机中的 始终评估为 true,因此它永远不会到达NotFound路线,我的建议是尝试将所有组件都放在NotFound其中在`<>...</>里面<Switch>&nbsp; &nbsp; <Route path='/login' component={Login}></Route>&nbsp; &nbsp; <Route path='/signup' component={SignUp}></Route>&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; <Header />&nbsp; &nbsp; &nbsp; &nbsp; <Route path='/cool-page' component={Cool}></Route>&nbsp; &nbsp; &nbsp; &nbsp; <Route path='/another-page' component={Another}></Route>&nbsp; &nbsp; &nbsp; &nbsp; <Route path='/' exact component={() => <Redirect to='/cool-page'></Redirect>}></Route>&nbsp; &nbsp; &nbsp; &nbsp; <Route path='/*' component={NotFound}></Route>&nbsp; &nbsp; </></Switch>

智慧大石

我认为你需要path完全删除该属性

小唯快跑啊

因为你有两条匹配的路线'/'。将其更改为'/*'匹配所有通配符路由。

一只名叫tom的猫

也许它没有到达路线的终点,因为<></>. <></>尝试使用一个组件和另一个开关来代替反应片段。我尝试了一些组合,这个有效:const WithHeader = ({ children }) => {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <div>Header</div>&nbsp; &nbsp; &nbsp; <div>{children}</div>&nbsp; &nbsp; </div>&nbsp; );};<Switch>&nbsp; &nbsp; <Route path="/login" component={() => "Login"}></Route>&nbsp; &nbsp; <Route path="/signup" component={() => "Sign Up"}></Route>&nbsp; &nbsp; <Route path="/404" component={() => "Not Found"}></Route>&nbsp; &nbsp; <WithHeader>&nbsp; &nbsp; &nbsp; &nbsp; <Switch>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path="/cool-page" component={() => "Cool Page"}></Route>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/another-page"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component={() => "Another Page"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ></Route>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exact&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component={() => <Redirect to="/cool-page"></Redirect>}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ></Route>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route render={() => <Redirect to="/404" />} />&nbsp; &nbsp; &nbsp; &nbsp; </Switch>&nbsp; &nbsp; </WithHeader></Switch>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript