为了账号安全,请及时绑定邮箱和手机立即绑定

React 路由器不会找不到页面

React 路由器不会找不到页面

白衣染霜花 2023-07-20 14:45:29
我有一个标题,我想在某些页面上显示。所以我把我想要的页面包裹在 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>
查看完整描述

4 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

我在文档中找不到它,但我的感觉是(我自己测试了它),<></>您的交换机中的 始终评估为 true,因此它永远不会到达NotFound路线,我的建议是尝试将所有组件都放在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>

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

    </>

</Switch>


查看完整回答
反对 回复 2023-07-20
?
智慧大石

TA贡献1946条经验 获得超3个赞

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



查看完整回答
反对 回复 2023-07-20
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

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



查看完整回答
反对 回复 2023-07-20
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

也许它没有到达路线的终点,因为<></>. <></>尝试使用一个组件和另一个开关来代替反应片段。我尝试了一些组合,这个有效:


const WithHeader = ({ children }) => {

  return (

    <div>

      <div>Header</div>

      <div>{children}</div>

    </div>

  );

};


<Switch>

    <Route path="/login" component={() => "Login"}></Route>

    <Route path="/signup" component={() => "Sign Up"}></Route>

    <Route path="/404" component={() => "Not Found"}></Route>


    <WithHeader>

        <Switch>

            <Route path="/cool-page" component={() => "Cool Page"}></Route>

            <Route

                path="/another-page"

                component={() => "Another Page"}

            ></Route>

            <Route

                path="/"

                exact

                component={() => <Redirect to="/cool-page"></Redirect>}

            ></Route>

            <Route render={() => <Redirect to="/404" />} />

        </Switch>

    </WithHeader>

</Switch>


查看完整回答
反对 回复 2023-07-20
  • 4 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信