【发布时间】:2021-06-27 19:06:39
【问题描述】:
我正在尝试使用 React 构建动态路由器。这个想法是从后端接收到的数据(对象)创建路由:
菜单对象:
items: [
{
name: "dashboard",
icon: "dashboard",
placeholder: "Dashboard",
path: "/",
page: "Dashboard",
exact: true,
},
{
name: "suppliers",
icon: "suppliers",
placeholder: "Suppliers",
path: "/suppliers",
page: "Suppliers",
exact: true,
}
]
路线挂钩:
export const RouteHook = () => {
// Dispatch to fetch the menu object from the backend
const dispatch = useDispatch();
dispatch(setMenu());
// Select the menu and items from Redux
const { items } = useSelector(getMainMenu);
// useState to set the routes inside
const [menuItems, setMenuItems] = useState([]);
const { pathname } = useLocation();
useEffect(() => {
// Loop trough the menu Items
for (const item of items) {
const { page, path, name, exact } = item;
// Import dynamically the route components
import(`../pages/${name}/${page}`).then((result) => {
// Set the routes inside the useState
setMenuItems(
<Route exact={exact} path={path} component={result[page]} />
);
});
}
// Check if pathname has changed to update the useEffect
}, [pathname]);
return (
<Switch>
{/* Set the routes inside the switch */}
{menuItems}
</Switch>
);
};
现在问题来了。并非所有组件都加载。通常会加载最后一个组件,并且当单击不同的路线时,组件不会更改。除非您进入页面并刷新 (F5)。
我在这里缺少什么?是否可以在 react 中创建完整的动态路由和组件?
【问题讨论】:
-
为什么你的
useEffect依赖于pathname?无论当前路径是什么,路径都是相同的。当前路径与正确Route的匹配由 react-router-dom 处理。 -
我发现我在那里犯了一个错误。我认为我需要检查路径是否已更改,如果是,请重新运行 useEffect。但从下面的答案中,我发现这是绝对错误的。
标签: javascript reactjs react-redux react-router react-hooks