搜索

首页  >  问答  >  正文

Reactjs路由页面显示为空白的解决方法

我正在使用Reactjs,并且现在正在尝试使用“动态路由”,但是页面显示为空白。这是我的路由文件:

export default function Router() {
  return useRoutes([
     {       
     path: "/",
     element: <Layout />,
     errorElement: <Page404 />,
     children: [
        { element: <HomePage />, index: true },
        { element: <User />, index: true },
                ],     
        },  
        ]); 
}

const HomePage = Loadable(lazy(() => import("../pages/HomePage")));
const User = Loadable(lazy(() => import("../pages/User")));
const Page404 = Loadable(lazy(() => import("../pages/Page404")));

我正在尝试访问(src/pages)中的“User.js”文件,这是我的User.js文件:

import React, { useEffect, useState } from "react";
import { useParams, withRouter } from "react-router";
import axios from "axios";
const User = (props) => {
    const params = useParams();
    const [users, setUsers] = useState({});
    useEffect(() => {
        async function fetchData() {
            const res = await axios(
                `https://jsonplaceholder.typicode.com/comments/${params.id}`
            );
            console.log("INDI", res.data);
            setUsers(res.data);
        }
        fetchData();
    }, []);
    return (
        <>
        <div>Hello worldddddddd</div>
        </>
    );
};

export default User;
P粉434996845P粉434996845486 天前573

全部回复(1)我来回复

  • P粉885035114

    P粉8850351142023-09-07 11:02:47

    问题在于你为两个子元素添加了index=true。你只能有一个索引页面

    示例:

    return useRoutes([
       {       
       path: "/",
       element: <Layout />,
       errorElement: <Page404 />,
       children: [
          { element: <HomePage />, index: true },
          { element: <User />},
                  ],     
          },  
          ]); 
    }
    
    const HomePage = Loadable(lazy(() => import("../pages/HomePage")));
    const User = Loadable(lazy(() => import("../pages/User")));
    const Page404 = Loadable(lazy(() => import("../pages/Page404")));

    你可以从这个问题的被接受的答案中了解更多关于index=true的目的。

    回复
    0
  • 取消回复