我想将默认路由设置为主页,我正在使用Reaction路由v5,但它不起作用,我正在try 这种方式,

Index.js

import React from "react";
import ReactDOM from "react-dom";
import "assets/css/App.css";
import 'assets/css/main.css'
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
import AuthLayout from "layouts/auth";
import AdminLayout from "layouts/admin";
import HomeLayout from "layouts/home";
import { ChakraProvider } from "@chakra-ui/react";
import theme from "theme/theme";
import { ThemeEditorProvider } from "@hypertheme-editor/chakra-ui";
import ErrorPage from "views/ErrorPage";

ReactDOM.render(
  <ChakraProvider theme={theme}>
    <React.StrictMode>
      <ThemeEditorProvider>
        <HashRouter>
          <Switch>
            <Route path={`/auth`} component={AuthLayout} />
            <Route path={`/admin`} component={AdminLayout} />
            <Route path={`/`} component={HomeLayout} />
            <Route path={'/home'} component={HomeLayout} />
            <Route path={'**'} exact={true} to='/' />
            {/* <Redirect exact from='/' to='/home'/> */}
          </Switch>
        </HashRouter>
      </ThemeEditorProvider>
    </React.StrictMode>
  </ChakraProvider>,
  document.getElementById("root")
);

在这里,其他路由是工作的,如关于,联系和主页,但默认路由不重定向到主页.

Routes.js

import React from "react";
import { Icon } from "@chakra-ui/react";
import {
  MdBarChart,
  MdPerson,
  MdHome,
  MdLock,
  MdOutlineShoppingCart,
} from "react-icons/md";
import MainDashboard from "views/admin/default";
import Profile from "views/admin/profile";
import DataTables from "views/admin/dataTables";
import SignInCentered from "views/auth/signIn";
import SignUp from "views/auth/signup";
import Home from "views/home";
import Contact from "views/contact";
import About from "views/about";


const routes = [
  {
    name: "Dashboard",
    layout: "/admin",
    path: "/default",
    icon: <Icon as={MdHome} width='20px' height='20px' color='inherit' />,
    component: MainDashboard,
  },
  {
    name: "Alumni",
    layout: "/admin",
    icon: <Icon as={MdBarChart} width='20px' height='20px' color='inherit' />,
    path: "/data-tables",
    component: DataTables,
  },
  {
    name: "Profile",
    layout: "/admin",
    path: "/profile",
    icon: <Icon as={MdPerson} width='20px' height='20px' color='inherit' />,
    component: Profile,
  },
  {
    name: "Sign In",
    layout: "/auth",
    path: "/sign-in",
    icon: <Icon as={MdLock} width='20px' height='20px' color='inherit' />,
    component: SignInCentered,
  },
  {
    name: "Sign In",
    layout: "/auth",
    path: "/sign-up",
    icon: <Icon as={MdLock} width='20px' height='20px' color='inherit' />,
    component: SignUp,
  },
  {
    name: "Landing Page",
    layout: "/Public",
    path: "/home",
    component: Home,
  },
  {
    name: "Contact Us",
    layout: "/Public",
    path: "/contact-us",
    component: Contact,
  },
  {
    name: "About Us",
    layout: "/Public",
    path: "/about-us",
    exact:'true',
    component: About,
  },
];

export default routes;

Navbar.js

    import {
    Box,
    Button,
    ButtonGroup,
    Container,
    Flex,
    HStack,
    IconButton,
    Stack,
    useBreakpointValue,
    useColorModeValue,
    useDisclosure, Image
} from '@chakra-ui/react'
import * as React from 'react'
import { FiMenu } from 'react-icons/fi'
import { HashLink as Link } from 'react-router-hash-link'
import { NavLink } from 'react-router-dom'

export const Nav = () => {
    const { isOpen, onOpen, onClose } = useDisclosure();
    const isDesktop = useBreakpointValue({
        base: false,
        lg: true,
    })
    return (
        <Flex
            py={2}
            px={4}
            bg="#fff"
            pos="fixed" w="100%" zIndex={2}
        >
            <Box w='100%'>
                <HStack spacing="10">
                    {isDesktop ? (
                        <>
                            <Flex alignItems="start" wrap="wrap" >
                                <Flex flexGrow={1} justify="center" /*border='1px'*/>
                                    {/* <Heading ml={[4, 0]}>Zensurance</Heading> */}
                                    <Box ml={[4, 8]}>
                                        <Image
                                            src='./assets/images/other/logo.png'
                                            alt=''
                                            w={250}
                                        />
                                    </Box>
                                </Flex>
                            </Flex>

                            <Flex justifyContent='end' fontSize='20' mr={5} fontWeight={500} flex="1">
                                <HStack spacing={10}>
                                    <NavLink to="/home" >Home</NavLink>
                                    <NavLink to="/about-us" >About</NavLink>
                                    <Link smooth to={{ pathname: "/home", hash: "testimonials" }}> Testimonials</Link>
                                    <Link smooth to={{ pathname: "/home", hash: "faq" }}> Faq</Link>
                                    <NavLink to="/contact-us" >Contact</NavLink>
                                </HStack>
                                <HStack ml={3}>
                                    <NavLink to='auth/sign-in'>
                                        <Button colorScheme='red'>Sign in</Button>
                                    </NavLink>
                                </HStack>
                            </Flex>
                        </>
                    ) : (
                        <>
                            <Flex alignItems="start" wrap="wrap" w='100%'>
                                <Flex flexGrow={1} justify="center" /*border='1px'*/>
                                    {/* <Heading ml={[4, 0]}>Zensurance</Heading> */}
                                    <Box ml={[4, 8]}>
                                        <Image
                                            src='./assets/images/other/logo.png'
                                            alt=''
                                            w={'280px'}
                                            h={'autopx'}
                                        />
                                    </Box>
                                </Flex>
                            </Flex>
                            <Flex justifyContent='end' spacing={2} w='100%'>
                                <IconButton
                                    variant="ghost"
                                    icon={<FiMenu fontSize="1.25rem" onClick={isOpen ? onClose : onOpen} />}
                                    aria-label="Open Menu"
                                />
                                <NavLink to='auth/sign-in'>
                                    <Button colorScheme='red'>Sign in</Button>
                                </NavLink>
                            </Flex>
                        </>
                    )}
                </HStack>

                {!isDesktop && isOpen ? (

                    <Stack justifyContent='center' fontSize='20' mr={5} fontWeight={500} direction={["column"]}>
                        <NavLink to="/home" >Home</NavLink>
                        <NavLink to="/about-us" >About</NavLink>
                        <Link smooth to={{ pathname: "/home", hash: "testimonials" }}> Testimonials</Link>
                        <Link smooth to={{ pathname: "/home", hash: "faq" }}> Faq</Link>
                        <NavLink to="/contact-us" >Contact</NavLink>
                    </Stack>
                )
                    :
                    ''
                }
            </Box>

        </Flex>
    )
}

HomyLayout.js

import React from "react";
import routes from "routes.js";
import { Redirect, Route, Switch } from "react-router-dom";
import { Box, useColorModeValue } from "@chakra-ui/react";
import { Nav } from "./header";
import Footer from "./footer";

export default function Home() {

  const getRoutes = (routes) => {
    return routes.map((prop, key) => {
      if (prop.layout === "/Public") {
        return (
          <Route
            path={prop.path}
            component={prop.component}
            key={key}
          />
        );
      } else {
        return null;
      }
    });
  };
  const authBg = useColorModeValue("white", "navy.900");
  document.documentElement.dir = "ltr";
  return (
    <Box
      bg={authBg}
      float='right'
      minHeight='100vh'
      height='100%'
      position='relative'
      w='100%'
      transition='all 0.33s cubic-bezier(0.685, 0.0473, 0.346, 1)'
      transitionDuration='.2s, .2s, .35s'
      transitionProperty='top, bottom, width'
      transitionTimingFunction='linear, linear, ease'>
      <Box mx='auto' minH='100vh'>
        <Nav />
        <Switch>
          {getRoutes(routes)}
        </Switch>
        <Footer />
      </Box>
    </Box>
  );
}

 

提前感谢……

Lorem Isum Dolor坐在一起,敬爱你的足尖精英.我的意思是说,我的意思是,我的意思是

推荐答案

如果我的理解是正确的,您希望HomeLayout组件成为"默认"路由/组件,那么只需将之前未由Switch组件匹配和呈现的任何路径重定向到"/home".

示例:

<HashRouter>
  <Switch>
    <Route path="/auth" component={AuthLayout} />
    <Route path="/admin" component={AdminLayout} />
    <Route path="/home" component={HomeLayout} />
    <Redirect to="/home" />
  </Switch>
</HashRouter>

它显示了您希望routes配置中的某些路由使用特定布局的基本要点.所有"公共"路由都将嵌套在"/home"根路径下,即它们应该是"/home/contact-us",依此类推,就像Navbar中的NavLink使用to='auth/sign-in'导航到"/auth"根目录.HomeLayout组件应该呈现从父"/home"路径相对构建的这些后代路由.

示例:

import { Switch, Route, useRouteMatch } from 'react-router-dom';

function HomeLayout() {
  const { path } = useRouteMatch(); // <-- "/home"

  const getRoutes = (routes) => {
    return routes
      .filter((route) => route.layout === "/Public") // <-- filter public routes
      .map((route) => (
        <Route
          key={`${path}${route.path}`}
          path={`${path}${route.path}`} // <-- build path, a.k.a. "/home/about-us"
          component={route.component}
          exact // <-- exactly match so route path order is irrelevant
        />
      ));
  };

  ...

  return (
    <Box
      ...
    >
      <Box mx="auto" minH="100vh">
        <Nav />
        <Switch>{getRoutes(routes)}</Switch>
        <Footer />
      </Box>
    </Box>
  );
}

更新路径配置,以准确修复"/home"上的Home组件渲染,而不是"/home/home"上.

const routes = [
  {
    name: "Dashboard",
    layout: "/admin",
    path: "/default",
    icon: <Icon as={MdHome} width="20px" height="20px" color="inherit" />,
    component: MainDashboard
  },
  {
    name: "Alumni",
    layout: "/admin",
    icon: <Icon as={MdBarChart} width="20px" height="20px" color="inherit" />,
    path: "/data-tables",
    component: DataTables
  },
  {
    name: "Profile",
    layout: "/admin",
    path: "/profile",
    icon: <Icon as={MdPerson} width="20px" height="20px" color="inherit" />,
    component: Profile
  },
  {
    name: "Sign In",
    layout: "/auth",
    path: "/sign-in",
    icon: <Icon as={MdLock} width="20px" height="20px" color="inherit" />,
    component: SignInCentered
  },
  {
    name: "Sign In",
    layout: "/auth",
    path: "/sign-up",
    icon: <Icon as={MdLock} width="20px" height="20px" color="inherit" />,
    component: SignUp
  },
  {
    name: "Landing Page",
    layout: "/Public",
    path: "/",      // <-- use "/" here instead of `"/home"`
    component: Home
  },
  {
    name: "Contact Us",
    layout: "/Public",
    path: "/contact-us",
    component: Contact
  },
  {
    name: "About Us",
    layout: "/Public",
    path: "/about-us",
    exact: "true",
    component: About
  }
];

Edit unable-to-set-default-route-in-react-router-v5

Javascript相关问答推荐

Mongoose post hook在使用await保存时不返回Postman响应

更改JSON中使用AJAX返回的图像的路径

无法访问Vue 3深度监视器中对象数组的特定对象值'

使用LocaleCompare()进行排序时,首先使用大写字母

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

我可以使用使用node.js创建的本地主机来存储我网站上提交的所有数据吗?没有SQL或任何数据库.只有HTML语言

如何将innerHTML字符串修剪为其中的特定元素?

使用auth.js保护API路由的Next.JS,FETCH()不起作用

FireBase FiRestore安全规则-嵌套对象的MapDiff

我怎样才能点击一个元素,并获得一个与 puppeteer 师导航页面的URL?

在Java脚本中构建接口的对象

Promise.race()返回已解析的promise ,而不是第一个被拒绝的promise

当S点击按钮时,我如何才能改变它的样式?

如何缩小函数中联合返回类型的范围

Reaction路由v6.4+数据API:重试加载程序而不显示错误

使用JavaScript或PHP从div ID值创建锚标记和链接

如何使用JavaScript将动态表上具有相同值的行与某些条件合并

使用jQuery在html Select 中查找正则表达式的值

为什么它是Object.hasOwn(x,y)!==Reflect.ownKeys(X).如果x是CSSStyleClaimation对象,而y是像';z-index';这样的连字符属性,则包含(Y)?

文本动画在其消失之前