首页 > 解决方案 > 在反应路由器中分离路由

问题描述

我将 React 与 react-router-dom 一起使用,我想要将我的路由分成不同的文件以获得更清晰的代码。假设我有SettingsRoutes.jsand ChatRoutes.js。每个都包含相关路由,如下所示:Settings.js

const SettingsRoutes = () => {
    const routes = [
        { path: '/help-center', Component: HelpCenter },
        { path: '/contact-us', Component: ContactUs },
        { path: '/terms', Component: TermsOfService },
        { path: '/guidelines', Component: CommunityGuidelines },
        { path: '/policy', Component: PrivacyPolicy },
        { path: '/account', Component: Account },
        { path: '/notifications', Component: Notifications },
        { path: '/report', Component: Report },
        { path: '/settings', Component: Settings },
        
    ]

    return (
        <>
            {routes.map(({ path, Component }) => (
                <Route path={path} exact render={props => <Component {...props} />} />
            ))}
        </>
    )
}

export default SettingsRoutes

聊天.js

import React from 'react'
import { Route, Switch } from 'react-router'
import Inbox from '../container/allChat'
import Chat from '../container/allChat/inbox/Chat'

const ChatRoutes = ({ socket, matches }) => {
    const BASE_URL = '/chat'
    const baseProps = { socket }
    const routes = [
        { path: `${BASE_URL}`, Component: Inbox, ownProps: baseProps },
        {
            path: `${BASE_URL}/rooms/:roomId/:name/:roomOwnerId`,
            Component: matches ? Inbox : Chat,
            ownProps: baseProps
        },
        { path: `${BASE_URL}/rooms/:mid`, Component: Inbox, ownProps: baseProps }
    ]
    return (
        <>
            {routes.map(({ path, Component, ownProps }) => (
                <Route
                    path={path}
                    exact
                    render={props => <Component {...props} {...ownProps} />}
                />
            ))}
        </>
    )
}

export default ChatRoutes

index.js(路由)

    <Switch>
            <ChatRoutes {...chatProps} />
            <SettingsRoutes/>   
        </Switch>
    )

现在由于某种原因只ChatRoutes.js被渲染但不是Settings.js 我认为它必须与Switch但不完全确定问题是什么有关。感谢您的帮助。

标签: javascriptreactjsreact-routercoding-style

解决方案


推荐阅读