reactJS имя параметров URL-адреса остается в URL-адресе, если это необязательно - PullRequest
0 голосов
/ 06 августа 2020

Я новичок с ReactJS, и у меня проблемы с необязательными параметрами в url.

Я использую response-router-dom 5.1.2.

Когда я пытаюсь создать маршрут с компонентом, у которого есть необязательные параметры, этот маршрут сохранит имя параметров, если для параметров нет значений. Если я создаю ссылку с параметром, все работает нормально.

Например, в моей боковой панели путь для доступа к AudioComponent (ссылка создается с помощью компонента маршрута):

<a class="sidebar-link" href="/callcenter/soundplayer/:agentName?/:date?">Audios</a>

My componentRoute:

{
  path: "/callcenter/soundplayer/:agentName?/:date?",
  name: "Audios",
  component: SoundFileRow,
  isShow: true,
  access: "staffAccess"
},

И мои маршруты. js (я загружаю шаблон, поэтому код маршрута уже был таким, за исключением условий)

const childRoutes = (Layout, routes, navBarAccess) =>   routes.map(({ children, path, realPath, component: Component, access }, index) =>
    children ? (
      // Route item with children
      children.map(({ path, component: Component , access}, index) => (
        <Route
          key={index}
          path={path}
          exact
          render={props => (
            (checkIsAuth())? 
            checkHasAccess(access) ? 
            <Layout>
              <Component {...props} />
            </Layout> :
            <AuthLayout>
              <Page404 />
            </AuthLayout> :
            <Redirect to={{ pathname: '/auth/sign-in' }} />
          )}
        />
      ))
    ) : (
      // Route item without children
      <Route
        key={index}
        path={path}
        exact
        render={props => (
          (checkIsAuth()) ? 
          (checkHasAccess(access)) ? 
            <Layout>
              <Component {...props} />
            </Layout> : 
            <AuthLayout>
              <Page404 />
            </AuthLayout> :
            (path !== "/auth/sign-in") ? 
            <Redirect to={{ pathname: '/auth/sign-in' }} /> : 
            <Layout>
              <Component {...props}  />
            </Layout>
        )}
      />
    )   );

и мой рендер:

render() {
       return (   <Router>
     <ScrollToTop>
       <Switch>
         {childRoutes(DashboardLayout, dashboardRoutes)}
         {childRoutes(DashboardLayout, defaultRoutes)}
         {childRoutes(AuthLayout, signInRoutes)}
         <Route
           render={() => (
             (checkIsAuth()) ? 
             <AuthLayout>
               <Page404 />
             </AuthLayout> : 
             <Redirect to={{ pathname: '/auth/sign-in' }} />
           )}
         />
       </Switch>
     </ScrollToTop>   </Router> );   }

У кого-то уже была эта проблема? Заранее спасибо за помощь :)

1 Ответ

0 голосов
/ 06 августа 2020

Я решил. Проблема заключалась в шаблоне, который использовал тот же путь для определения параметров URL-адреса и для отображения URL-адреса в href. Я просто создаю новый параметр в своем компоненте:

{
      path: "/callcenter/soundplayer",
      realPath: "/callcenter/soundplayer/:agentName?/:date?",
      name: "Audios",
      component: SoundFileRow,
      isShow: true,
      access: "staffAccess"
    },

Затем добавляю его в свой маршрутизатор. js:

    const childRoutes = (Layout, routes, navBarAccess) =>
routes.map(({ children, path, realPath, component: Component, access }, index) =>
  children ? (
      // Route item with children
      children.map(({ path, realPath, component: Component , access}, index) => (
        <Route
        key={index}
        path={realPath}
        exact
        render={props => (
          (checkIsAuth())? 
          checkHasAccess(access) ? 
          <Layout>
          <Component {...props} />
          </Layout> :
          <AuthLayout>
          <Page404 />
          </AuthLayout> :
          <Redirect to={{ pathname: '/auth/sign-in' }} />
          )}
        />
        ))
      ) : (
      // Route item without children
      <Route
      key={index}
      path={realPath}
      exact
      render={props => (
        (checkIsAuth()) ? 
        (checkHasAccess(access)) ? 
        <Layout>
        <Component {...props} />
        </Layout> : 
        <AuthLayout>
        <Page404 />
        </AuthLayout> :
        (path !== "/auth/sign-in") ? 
        <Redirect to={{ pathname: '/auth/sign-in' }} /> : 
        <Layout>
        <Component {...props}  />
        </Layout>
        )}
        />
        )
      );

Надеюсь, он будет полезен для кого-то днем!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...