将路由分组为组件内部的React Router Switch语句不会转到“未找到”路由

时间:2018-11-23 12:03:30

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

如果未找到路由,我尝试呈现“未找到”页面。我将路由分隔为模块。因此,当我执行switch语句时,在开关底部添加未找到的页面,例如:

const AccessRoutes = () => {
return (
    <React.Fragment>
        <Route path="/login" exact component={Login}/>
        <Route path="/register" exact component={Register} />
        <Route path="/forgot-password" exact component={ForgotPassword}/>
    </React.Fragment>
       )
}
export default () => {
    return (
     <Switch>
         <AccessRoutes/>
         <Route render={() => <div>Not found</div>}
     </Switch>
    )
}

当您输入不在AccessRoutes上的路径时,找不到的路径将永远不会匹配,例如/hey显示空白屏幕。如果我放置路线而没有将它们包装在另一个组件中,那么它将起作用。

我想念什么?

1 个答案:

答案 0 :(得分:1)

也许这可以帮助您:

export const routes = [
    {
        path: '/login',
        exact: true,
        component: Login
    }, {
        path: '/register',
        exact: true,
        component: Register
    }, {
        path: '/forgot-password',
        exact: true,
        component: ForgotPassword
    }, {
        path: '*',
        component: () => <div>Not found</div>
    }
];

export default () => {
    return (
        <Switch>
            {
                routes.map(
                    (route, index) => <Route key={index} {...route}/>
                )
            }
        </Switch>
    )
}