javascript 使用Redux和React-Router-DOM数据路由器

dffbzjpn  于 2024-01-05  发布在  Java
关注(0)|答案(1)|浏览(124)

我可以用下面的方式在路由器上使用Redux吗?还有,有没有理由用这种方式而不是使用路由器模块的钩子?

import { createBrowserRouter, RouterProvider } from "react-router-dom";
import HomePage from "./pages/HomePage";
import RootLayout from "./components/RootLayout";
import SearchPage from "./pages/SearchPage";
import WeatherPage from "./pages/WeatherPage";
import SettingsPage from "./pages/SettingsPage";
import { loader as HomePageLoader } from "./pages/HomePage";
import { useDispatch, useEffect } from "react-redux";

let router = "";

function App() {
  const dispatch = useDispatch();

  useEffect(() => {
    router = createBrowserRouter([
      {
        path: "/",
        element: <RootLayout />,
        children: [
          {
            index: true,
            element: <HomePage />,
            loader: () => {
              HomePageLoader(dispatch);
            }
          },
          { path: "search", element: <SearchPage /> },
          { path: "weather", element: <WeatherPage /> },
          { path: "settings", element: <SettingsPage /> }
        ]
      }
    ]);
  }, []);

  return (
    <RouterProvider router={router}>
    </RouterProvider>
  );
}

export default App;

字符串

2ul0zpep

2ul0zpep1#

当然。但是,与其使用useEffect钩子来改变一个局部“全局”router变量,不如使用useMemo钩子来记忆router,并在作用域中关闭dispatch函数。
另外,useEffect不是react-redux导出。
范例:

import { useMemo } from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { useDispatch } from "react-redux";
import HomePage, { loader as homePageLoader } from "./pages/HomePage";
import RootLayout from "./components/RootLayout";
import SearchPage from "./pages/SearchPage";
import WeatherPage from "./pages/WeatherPage";
import SettingsPage from "./pages/SettingsPage";

function App() {
  const dispatch = useDispatch();

  const router = useMemo(() => {
    return createBrowserRouter([
      {
        path:"/",
        element: <RootLayout />,
        children: [
          {
            index: true,
            element: <HomePage />,
            loader: homePageLoader(dispatch),
          }
          { path: "search", element: <SearchPage /> },
          { path: "weather", element: <WeatherPage /> },
          { path: "settings", element: <SettingsPage /> }
        ]
      }
    ]);
  }, [dispatch]);

  return <RouterProvider router={router} />;
}

export default App;

字符串
确保homePageLoader是一个curried函数,以便可以将dispatch函数传递给它,并返回一个传递给加载器属性的函数。
范例:

const loader = dispatch => ({ params, request }) => {
  // loader logic
};

相关问题