搜尋

首頁  >  問答  >  主體

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粉434996845449 天前552

全部回覆(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
  • 取消回覆