为什么组件没有在使用反应路由的反应 JS 中呈现在父布局中? [英] why component is not rendered in parent layout in react JS using react routing?

查看:43
本文介绍了为什么组件没有在使用反应路由的反应 JS 中呈现在父布局中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种不同的前端和管理面板布局.管理面板的组件在管理布局中正确呈现,但对于前端,它没有正确切换路由,也没有在前端布局中呈现.当我不在 index.js 中使用精确属性时,它甚至不适用于管理面板路由.我也咨询过这个链接不使用 React Router v4 渲染的嵌套路由但它对我不起作用.

从layouts/Dashboard/Dashboard.jsx"导入仪表板;从组件/前端/登录"导入登录;从layouts/Frontend/Frontend.jsx"导入前端;从layouts/Dashboard/AdminAuth.jsx"导入AdminLogin;var indexRoutes = [{ 路径:/",名称:前端",组件:前端,exactPro:true},{ 路径:/登录",名称:FrontendLogin",组件:登录,exactPro:false},{ path: "/Admin", name: "Home", component: Dashboard,exactPro:false },{ 路径:/Admin-login",名称:AdminLogin",组件:AdminLogin,exactPro:false}];导出默认索引路由;

Index.js

从react"导入React;从react-dom"导入 ReactDOM;从'react-router-dom'导入{路由器,路由,交换机}从routes/index.jsx"导入 indexRoutes;从'./helper/history'导入{历史};从./redux/store/index"导入商店;从react-redux"导入{提供者};ReactDOM.render(<提供者商店={商店}><路由器历史={历史} ><开关>{indexRoutes.map((prop, key) => {return <Route exact={prop.exactPro} path={prop.path} component={prop.component} key={key}/>;})}</开关></路由器></提供者>,document.getElementById("root"));

.......

从components/Admin/Dashboard"导入仪表板;从视图/用户配置文件/用户配置文件"导入用户配置文件;const 仪表板路由 = [{路径:/管理员/仪表板",name: "仪表盘",图标:pe-7s-graph",组件:仪表板,显示菜单:真,showMenuFront:假,iconImagePath:dashboardIcon,许可:'两者'},{路径:/管理员/用户",name: "用户资料",图标:pe-7s-user",组件:用户配置文件,显示菜单:假,showMenuFront:假,许可:'两者'},{ 重定向:true,路径:/Admin",到:/Admin/dashboard",名称:Dashboard"}];导出默认的dashboardRoutes;

........

从'react'导入React;从'react-router-dom'导入{路由,重定向};export const AdminAuthRoute = ({ component: Component, ...rest }) =>(<Route {...rest} render={(props, matchProps) =>(localStorage.getItem('admin-user')?<组件{...props} {...matchProps}/>: <重定向到={{ pathname: '/Admin-login', state: { from: props.location } }}/>)}/>)

.........

import React, { Component } from "react";import { Switch, Redirect } from "react-router-dom";从routes/dashboard.jsx"导入dashboardRoutes;从'helper/PrivateRouteAdmin'导入{AdminAuthRoute};类 DashboardPage 扩展组件 {构造函数(道具){超级(道具);}使成为() {返回 (<div className="包装器"><div id="main-panel" className="main-panel" ref="mainPanel"><开关>{dashboardRoutes.map((prop, key) => {console.log("prop 重定向", prop.redirect);如果(prop.redirect){return <Redirect from={prop.path} to={prop.to} key={key} test="haha"/>;}console.log('prop.path 111', prop.path);返回 (<AdminAuthRoute path={prop.path} component={prop.component} key={key}/>);})}</开关><页脚/>

);}}导出默认仪表板;

......

 import Home from "components/FrontEnd/Home";从components/FrontEnd/HowItWorks"导入 HowItWorks;从components/FrontEnd/AboutUs"导入AboutUs;const FrontEndRoutes = [{小路          : "/",名称 : "家",组件:首页,显示菜单:真,1号},{路径:/How_It_Works",name : "它是如何工作的",组件:HowItWorks,显示菜单:真,2号},{路径:/About_Us",name : "关于我们",组件:关于我们,显示菜单:真,数量 : 3}];导出默认的 FrontEndRoutes;

.........

从'react'导入React;从'react-router-dom'导入{路由,重定向};export const FrontEndAuthRoute = ({ component: Component, ...rest }) =>(<Route {...rest} render={(props, matchProps) =>(localStorage.getItem('音乐导演')?<组件{...props} {...matchProps}/>:<重定向到={{路径名:'/登录',状态:{来自:props.location}}}/>)}/>)

.................

import React, { Component } from "react";import { Switch, Redirect } from "react-router-dom";从routes/FrontEndRoutes.jsx"导入FrontEndRoutes;导入 { FrontEndAuthRoute } from 'helper/PrivateRouteFrontEnd';类前端扩展组件{构造函数(道具){超级(道具);}使成为() {返回 (<div className="包装器"><div id="main-panel" className="main-panel" ref="mainPanel"><开关>{FrontEndRoutes.map((prop, key) => {如果(prop.redirect){return <Redirect from={prop.path} to={prop.to} key={key} test="haha"/>;}返回 (<FrontEndAuthRoute path={prop.path} component={prop.component} key={key}/>);})}</开关>

);}}导出默认前端;

解决方案

在编写嵌套路由时需要注意很多事情

  1. 当你有嵌套的路由时,你需要确保父路由没有确切的关键字.例如,带有 path = '/' 和子路由 /home 的路由不会在 /home 上渲染 Home 组件,因为顶部级别本身不匹配.
  2. 您需要确保在 Switch 组件中编写路由时,前缀路由路径位于开头.

考虑到以上几点,您的应用需要进行以下更改

从layouts/Dashboard/Dashboard.jsx"导入仪表板;从组件/前端/登录"导入登录;从layouts/Frontend/Frontend.jsx"导入前端;从layouts/Dashboard/AdminAuth.jsx"导入AdminLogin;var indexRoutes = [{ 路径:/Admin-login",名称:AdminLogin",组件:AdminLogin,exactPro:false}{ 路径:/登录",名称:FrontendLogin",组件:登录,exactPro:false},{ path: "/Admin", name: "Home", component: Dashboard,exactPro:false },{ 路径:/",名称:前端",组件:前端,exactPro:false},];导出默认索引路由;

<小时>

从components/FrontEnd/Home"导入Home;从components/FrontEnd/HowItWorks"导入 HowItWorks;从components/FrontEnd/AboutUs"导入AboutUs;const FrontEndRoutes = [{路径:/How_It_Works",name : "它是如何工作的",组件:HowItWorks,显示菜单:真},{路径:/About_Us",name : "关于我们",组件:关于我们,显示菜单:真},{小路          : "/",名称 : "家",组件:首页,显示菜单:真},];导出默认 FrontEndRoutes;

I have two different layouts for front end and admin panel.Components for admin panel rendered correclty in admin layout but for front end it doesn't switch routes correctly and does not rendered in front end layout. When i don't use exact property in index.js it is even doesn't work for admin panel routes as well. I have consult this link as well Nested Routes not rendering with React Router v4 but it doesn't work for me.

import Dashboard from "layouts/Dashboard/Dashboard.jsx";
import Login from "components/FrontEnd/Login";
import Frontend from  "layouts/Frontend/Frontend.jsx";
import AdminLogin from  "layouts/Dashboard/AdminAuth.jsx";


var indexRoutes = [

    { path: "/", name: "Frontend", component: Frontend , exactPro:true},
    { path: "/login", name: "FrontendLogin", component: Login , exactPro:false},
    { path: "/Admin", name: "Home", component: Dashboard, exactPro:false },
    { path: "/Admin-login", name: "AdminLogin", component: AdminLogin, exactPro:false}

];

export default indexRoutes;

Index.js

import React from "react";
import ReactDOM from "react-dom";
import { Router, Route, Switch } from 'react-router-dom'
import indexRoutes from "routes/index.jsx";
import { history } from './helper/history';
import store from "./redux/store/index";
import { Provider } from "react-redux";

ReactDOM.render(
    <Provider store={store}>
        <Router history={history} >
            <Switch>
              {indexRoutes.map((prop, key) => {
                return <Route exact={prop.exactPro}  path={prop.path} component={prop.component} key={key} />;
              })}
            </Switch>
        </Router>
    </Provider>,
  document.getElementById("root")
);

.......

import Dashboard from "components/Admin/Dashboard";
import UserProfile from "views/UserProfile/UserProfile";

const dashboardRoutes = [
  {
    path: "/Admin/dashboard",
    name: "Dashboard",
    icon: "pe-7s-graph",
    component: Dashboard,
    showMenu:true,
    showMenuFront:false,
    iconImagePath:dashboardIcon,
    permission:'both'
  },
  {
    path: "/Admin/user",
    name: "User Profile",
    icon: "pe-7s-user",
    component: UserProfile,
    showMenu:false,
    showMenuFront:false,
    permission:'both'
  },
  { redirect: true, path: "/Admin", to: "/Admin/dashboard", name: "Dashboard" }
];

export default dashboardRoutes;

.........

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

export const AdminAuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props, matchProps) => (
        localStorage.getItem('admin-user') 
        ? <Component {...props} {...matchProps} /> 
        : <Redirect to={{ pathname: '/Admin-login', state: { from: props.location } }} />
    )} />
)

..........

import React, { Component } from "react";
import {  Switch, Redirect } from "react-router-dom";
import dashboardRoutes from "routes/dashboard.jsx";
import {  AdminAuthRoute } from 'helper/PrivateRouteAdmin';

class DashboardPage extends Component {
  constructor(props) {
    super(props);
  }


  render() {

    return (
      <div className="wrapper">
        <div id="main-panel" className="main-panel" ref="mainPanel">
          <Switch>
            {
              dashboardRoutes.map((prop, key) => {
                console.log("prop redirect", prop.redirect);
                if (prop.redirect){
                  return <Redirect from={prop.path} to={prop.to} key={key} test="haha" />;
                }
                console.log('prop.path 111', prop.path);
                return (
                  <AdminAuthRoute   path={prop.path}  component={prop.component} key={key}  />
                );
              })
            }
          </Switch>
          <Footer />
        </div>
      </div>
    );
  }
}


export default Dashboard;

......

 import Home from "components/FrontEnd/Home";
    import HowItWorks from "components/FrontEnd/HowItWorks";
    import AboutUs from "components/FrontEnd/AboutUs";

    const FrontEndRoutes = [
      {
        path          : "/",
        name          : "Home",
        component     : Home,
        showMenu      : true,
        number        : 1
      },
      {
        path          : "/How_It_Works",
        name          : "How it works",
        component     : HowItWorks,
        showMenu      : true,
        number        : 2
      },
      {
        path          : "/About_Us",
        name          : "About Us",
        component     : AboutUs,
        showMenu      : true,
        number        : 3
      }
    ];

    export default FrontEndRoutes;

...........

import React from 'react';
import { Route, Redirect } from 'react-router-dom';

export const FrontEndAuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={(props, matchProps) => (
        localStorage.getItem('music-director') 
        ? <Component {...props} {...matchProps} /> 
        : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)

...............

import React, { Component } from "react";
import {  Switch, Redirect } from "react-router-dom";
import FrontEndRoutes from "routes/FrontEndRoutes.jsx";
import {  FrontEndAuthRoute } from 'helper/PrivateRouteFrontEnd';

class Frontend extends Component {
  constructor(props) {
    super(props);
  }
  render() {

    return (
      <div className="wrapper">
        <div id="main-panel" className="main-panel" ref="mainPanel">
          <Switch>
            {
              FrontEndRoutes.map((prop, key) => {
                if (prop.redirect){
                    return <Redirect from={prop.path} to={prop.to} key={key} test="haha" />;
                }
                return (
                    <FrontEndAuthRoute   path={prop.path}  component={prop.component} key={key}  />
                );

              })
            }
          </Switch>
        </div>
      </div>
    );
  }
}
export default Frontend;

解决方案

There are multiple things that you need to take care of while writing nested Routes

  1. When you have nested Routes, you need to make sure that the parent route doesn't have an exact keyword. For instance, a route with path = '/' with child route /home won't render Home component on /home because the the top level itself won't match.
  2. You need to make sure that while writing Routes within the Switch component, the prefix route paths are at the start.

Considering the above points, the following changes will need to be made in your app

import Dashboard from "layouts/Dashboard/Dashboard.jsx";
import Login from "components/FrontEnd/Login";
import Frontend from  "layouts/Frontend/Frontend.jsx";
import AdminLogin from  "layouts/Dashboard/AdminAuth.jsx";


var indexRoutes = [

    { path: "/Admin-login", name: "AdminLogin", component: AdminLogin, exactPro:false}
    { path: "/login", name: "FrontendLogin", component: Login , exactPro:false},
    { path: "/Admin", name: "Home", component: Dashboard, exactPro:false },
    { path: "/", name: "Frontend", component: Frontend , exactPro:false},

];

export default indexRoutes;


import Home from "components/FrontEnd/Home";
import HowItWorks from "components/FrontEnd/HowItWorks";
import AboutUs from "components/FrontEnd/AboutUs";

const FrontEndRoutes = [
  {
    path          : "/How_It_Works",
    name          : "How it works",
    component     : HowItWorks,
    showMenu      : true
  },
  {
    path          : "/About_Us",
    name          : "About Us",
    component     : AboutUs,
    showMenu      : true
  },
  {
    path          : "/",
    name          : "Home",
    component     : Home,
    showMenu      : true
  },
];

export default FrontEndRoutes;

这篇关于为什么组件没有在使用反应路由的反应 JS 中呈现在父布局中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆