javascript React和useRoutes的问题

j9per5c4  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(87)

我正在尝试使用React和useRoutes,但是我收到一个错误,什么都没有显示。我不知道问题出在哪里,你能帮助我吗?非常感谢
这是错误

routes.js:12 Uncaught TypeError: Cannot read properties of undefined (reading 'createElement')
    at routes.js:12:17
    ..

这些是我的文件
jsx包含BrowserRouter的导入

import Index from './Index.jsx';
import { BrowserRouter as Router, Link } from "react-router-dom";
import { Menu } from './Menu.jsx';

export const App = () => (
    <div>
        <Router>
            <Menu />
            <Index />
        </Router>
    </div>
);

包含useRoutes的索引. jsx

import { useRoutes } from "react-router-dom";
import { routes } from "./routes";

export const Component = () => {
  let element = useRoutes(routes);
  return element;
};

export default Component;

router.js,其中将声明所有路由

import { React } from "react";
import { Home } from './Home.jsx';
import { ErrorPage } from './ErrorPage.jsx';

export const routes = [
    {
        path:'/', 
        element:<Home />
    },
    { 
        path:'*',             
        element:<ErrorPage /> 
    }
];

包含站点菜单和相应链接的Menu.jsx

import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import { pages } from '../../data/pages';

export const MenuTop = () => {
    const [myPages, setMyPages] = useState(pages);
    const [pageToDisplay, setPageToDisplay] = useState("/");

    const displayPage = (page) => { 
        setPageToDisplay(page.url);
    }

    return (
        <Router>
            <div className="ui menu">
                {myPages.map((el) => {
                    const { id, name, url } = el;
                    return (
                        <Link to={url} key={id} className={`item ${pageToDisplay == url ? "active" : ""}`} onClick={() => displayPage({url})}>{name}</Link>
                    );
                })}
            </div>
        </Router> 
    );
}
z4bn682m

z4bn682m1#

问题是你导入了错误的React,使用了一个命名的导出而不是默认的。下面是router.js/routes.js中的错误:
在第一行,import { React } from 'react'

import { React } from "react";
import { Home } from './Home.jsx';
import { ErrorPage } from './ErrorPage.jsx';

export const routes = [
    {
        path:'/', 
        element:<Home />
    },
    { 
        path:'*',             
        element:<ErrorPage /> 
    }
];

将其更改为默认导出:

import React from "react";
import { Home } from './Home.jsx';
import { ErrorPage } from './ErrorPage.jsx';

export const routes = [
    {
        path:'/', 
        element:<Home />
    },
    { 
        path:'*',             
        element:<ErrorPage /> 
    }
];

这应该可以解决问题。

相关问题